The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.
Input Specification:
Each input file contains one test case which gives the positive N (<=230).
Output Specification:
For each test case, print the number of 1's in one line.
Sample Input:12Sample Output:
5
给定一个正整数n,求1到n中所有数所含的1的个数。这里的思路是对数的每一位分析,假设某一位为1时,有多少种可能,然后相加得到结果。比如32104,对于0的那一位,大于31119的数在该位都不会出现1,观察311,1,9,容易知该位为1的可能为有312*10种(左边和右边都可以为0,所以是(311+1)*(9+1));对于1的那一位,首先大于32099该位为1的可能有5种,然后小于等于32099的情况和上面0的情况一样(32*100种),把两种情况得到的数相加即可;对于2的那一位,大于31999的数在该位不会出现1,观察3,1,999,容易知该位为1的可能有4*1000种。按照在以上思路对n的每一位进行计算然后累加即可得到答案。为了方便处理每一位,输入的格式设为字符串。
代码:
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
string n;
cin>>n;
int res=0;
for(int i=0;i<n.size();i++)
{
int mid=n[i]-'0';
int left=atoi(n.substr(0,i).c_str());
int right=atoi(n.substr(i+1,n.size()).c_str());
int ex=n.size()-i-1;
if(mid==0) res+=left*pow(10,ex);
else if(mid==1) res+=((right+1)+left*pow(10,ex));
else res+=(left+1)*pow(10,ex);
}
cout<<res;
}