问题1:写一个函数f(N),返回1到N之间出现的“1”的个数。
假设N=abcde,分别统计a、b、c、d、e位上出现的1的个数,它们之和就是总的1的个数
a位上1的个数:
若a>1,则为10000;
若a=1,则为bcde+1;
a不可能为0。
b位上1的个数:
若b>1,则为(a+1)*1000;
若b=1,则为(a+1)*(cde+1);
若b=0,则为a*1000;
c位上1的个数:
若c>1,则为(ab+1)*100;
若c=1,则为(ab+1)*(de+1);
若c=0,则为ab*100;
d位上1的个数:
若d>1,则为(abc+1)*10;
若d=1,则为(abc+1)*(e+1);
若d=0,则为abc*10;
e位上1的个数:
若e>1,则为(abcd+1)*1;
若e=1,则为(abcd+1)*(0+1);
若e=0,则为abcd*1;
根据上面的规律,写出以下程序
///统计1~N中含1的个数
#include<iostream>
using namespace std;
int main()
{
int N; //输入的N
int num=0;//记录1的个数
cin>>N;
int high=0;//存储当前位的高位,如ab
int low=0;//存储当前位的低位,如de
int curr=0;//存储当前位,如c
int beishu=1;
while(N)
{
curr=N%10;
high=N/10;
if(curr==0)
{
num+=high*beishu;
}
else if(curr==1)
{
num+=(high+1)*(low+1);
}
else
num+=(high+1)*beishu;
low+=curr*beishu;
beishu*=10;
N/=10;
}
cout<<num<<endl;
return 0;
}