剑指offer(31)1到n中n出现的次数
简单解法。非最优解。第二种方案参见《程序员代码面试指南》p430
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
if(n < 1){
return 0;
}
int count = 0;
for(int i = 1;i != n+1;i++){
count += CountOne(i);
}
return count;
}
public int CountOne(int n){
int res = 0;
while(n != 0){
if(n % 10 == 1){
res++;
}
n = n / 10;
}
return res;
}
}