/*问题描述:给定一个十进制数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
*/
#include <iostream>
using namespace std;
//给定一个整数n,返回该整数各个位上1的总算
int InnerCount(int n)
{
int inner_count = 0;
while (n > 0)
{
if (n % 10 == 1)
{
++inner_count;
}
n /=10;
}
return inner_count;
}
//给定一个整数n,返回从1到n的所有数的各个位1的总算
int Count(int n)
{
int count = 0;
for (int i=1; i<=n; ++i)
{
count += InnerCount(i);
}
return count;
}
int main()
{
int number;
cout<<"input the number: ";
cin>>number;
cout<<"the count of '1': "<<Count(number)<<endl;
}