将数字放在一个sring里面,循环遍历判断里面1就好了
String temp = "";
int result = 0;
for(int i = 1;i<n+1;i++){
temp = String.valueOf(i);
for(int j = 0;j<temp.length();j++){
if(temp.charAt(j) == '1'){
result++;
}
}
}
return result;
找规律
int cnt = 0;
for (int m = 1; m <= n; m *= 10) {
int a = n / m, b = n % m;
cnt += (a/10+(a%10>1?1:0)) * m + (a % 10 == 1 ? b + 1 : 0);
}
return cnt;
网友评论