1.统计1~n中数字1出现的个数:
public class TestDemo{
public static void main(String[] args){
int count = 0;
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int i=1;i<=n;i++){
int src = i;
while(src !=0){
if(src % 10==1){
count++;
}
src/=10;
}
}
System.out.println(count);
}
}
2.字符串转整型:例如给一个数字字符串“123”转成数组123,“-123”转成数字-123,“a-+123”转成数字123:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
char[] ch = str.toCharArray();//这个得特别记住,把字符串转换为char字符数组,用数组操作起来更为简便
int count = getCount(ch);
int size = 0;
int[] arr = new int[count];
int flag = 1;
for(int i=0;i<ch.length;i++){
if(ch[i]>='0'&& ch[i]<='9') {
arr[size++] = ch[i] - '0';//减去字符0所对应的ASCII码值就是相应的整型数字
}
if(ch[i] == '-'){
flag *=-1;
}
int result = 0;
int exp = count;
for(int i=0;i<count;i++){
result+=arr[i]*Math.pow(10,--exp);
}
result*=flag;
System.out.println(result);
}
}
}
代码就不多说,我觉得这个题里面用到的想法很好,就是如果要把字符09转换成对应的数字09就减去字符0所对应的ASCII码值,众所周知字符09所对应的ASCII码值是4857,如果要从字符0得到整型数字0那就减去相差的48就好了
3. 将i am a student ->转成 student a am i
public static void main(String[] args) {
String str = "i am a student";
//str转成字符串数组
String[]arr = str.split(" ");
for(int i=0;i<arr.length/2;i++){
String temp = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp;
}
String result = "";
System.out.println(Arrays.toString(arr));
for(int i=0;i<arr.length;i++){
result = result+arr[i]+" ";
}
System.out.println(result);
}
}