简单——算法训练
01计算水仙花数
~~~public class Daffodils01Test {
public static void main(String[] args) {
//个、十、百位值
int bits,ten,hundred;
for (int i=100;i<1000;i++){
hundred = i/100;
ten = (i%100)/10;
bits = (i%100)%10;
if (i==(Math.pow(ten,3)+Math.pow(bits,3)+Math.pow(hundred,3))){
System.out.println(i);
}
}
}
}
02输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
import java.util.Scanner;
public class Statistical02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char[] chars = str.toCharArray();
//对应索引分别统计:0:是英文 1:是数字 2:是空格 3:是其它字符
int[] count = new int[4];
//给初始值
for (int i = 0; i < count.length; i++) {
count[i]=0;
}
for (int i = 0; i < chars.length; i++) {
//英文字母的判断 数字的判断 空格判断 其它字符的判断
if((chars[i]>=65&&chars[i]<=90)||(chars[i]>=97&&chars[i]<=122)){
count[0]++;
}else if(chars[i]>=49&&chars[i]<=57){
count[1]++;
}else if(chars[i]==32){
count[2]++;
}else {
count[3]++;
}
}
for (int i = 0; i < count.length; i++) {
System.out.print(count[i]+" ");
}
}
}
03、排序两种算法
import java.util.Arrays;
public class SortTest {
public static void main(String[] args) {
int[] num = {3,2,1,9,10};
// bubbling(num);//冒泡排序
selectionSort(num);//选择排序
System.out.println(Arrays.toString(num));
}
public static void selectionSort(int[] num){
int minIndex = 0;
for (int i = 0; i < num.length-1; i++) {
//minIndex记录最小值索引
minIndex = i;
for (int j = i+1; j < num.length ; j++) {
if(num[minIndex]>num[j]){
minIndex = j;
}
}
if(minIndex!=i){
int temp = num[minIndex];
num[minIndex] = num[i];
num[i] = temp;
}
}
}
public static void bubbling(int[] num){
//外层控制比较轮次,i,内层j控制比较次数
for (int i = 0;inum[j+1]){
int temp = num[j];
num[j] = num[j+1];
num[j+1]=temp;
}
}
}
}
}