给定一个十进制正整数 N,写下从 1开始,到 N的所有整数,然后数一下其中出现的所有“1”的个数。
例如:
N=2,写下 1,2。这样只出现了 1个“1”。
N=12,我们会写下 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11, 12。这样,1的个数是 5。
解决方法:取N各位数位上可能出现1的个数总和!
java实现代码:
//count为1的总数,factor为正在取的数的因子
//lowernum为要取的数位左边的数,highernum为要取的数位右边的数
public static long count_of_1_from_1_to_n(long n){
long count = 0,factor = 1,lowernum, currnum,highernum;
while(n/factor != 0){
lowernum = n - (n/factor)*factor;
currnum = (n/factor)%10;
highernum = n/(factor*10);
if(currnum == 0){
count += highernum*factor;
}else if(currnum == 1){
count += highernum*factor+lowernum+1;
}else{
count += (highernum+1)*factor;
}
factor = factor*10;
}
return count;
}