剑指offer中给出了解题的思路,但程序略嫌繁琐,它先将整数转化成字符串之后进行操作,本文给出了一个相对简洁程序。
具体思路如下:
(123456)的1个数 = 23456+1 + 5*pow(10,5-1) + (23456)的1个数
(23456)的1个数 = 3456+1 + 4*pow(10,4-1) + (3456)的1个数
。。。
代码如下:
#include<iostream>
using namespace std;
int count1number(unsigned N){
int k=0; //N的总位数-1
int tmp=1;//10**(k-1)
while(N>=tmp*10){
tmp*=10;
k++;
}
int count =0;
while(tmp>=1){
if((N/tmp)%10!=0){
if(N/tmp==1)
count +=N%tmp+1+N/tmp*k*(tmp/10);
else
count +=tmp+N/tmp*k*(tmp/10);
}
N%=tmp;
tmp/=10;
k--;
}
return count;
}
int count1BF(unsigned N){
int tmp=1;
int count=0;
while(N/tmp){
if((N/tmp)%10==1)
count++;
tmp*=10;
}
return count;
}
int main(){
int N=100;
for(N=0;N<101;++N){
int count =0;
for(int i=1;i<=N;i++){
count+=count1BF(i);
}
int count2=count1number(N);
cout<<"N:"<<N<<" "<<count<<" "<<count2<<endl;
}
return 0;
}