1049. Counting Ones (30)
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
这是一道经典的数1问题。这道题的意思是给一个整数N,计算出从1到N的所有数中出现“1”的次数。思路如下:
对于一串 n位的数A[n-1] A[n-2]……A[0] ,分别计算每一位上出现“1”的次数。对于任意不在最高位的第K位,可以以K为界限将整串数分为高位”high“(A[N-1]至A[K+1])和低位”low“(A[K-1]至A[0]) ,设低位位数为lsize(lsize>=0) 由此第K位上出现”1“的次数 n 如下:
1) 当A[K]>1时,n=(high+1)*pow(10,lsize)。 例如N为121时,第2位上出现1的次数即为(1+1)*10^1=20,也就是保持第二位不变从010计数到019,共20次
2) 当A[K]=1时,n=(high)*pow(10,lsize)+low+1。例如N为112时,第2位上出现1的次数即为1*10^1+2+1=13,也就是保持第二位不变从010计数到112,共13次
3) 当A[K]=0时,n=high*pow(10,lsize). 例如N为103时,第2位上出现1的次数即为1*10^1=10,也就是保持第二位不变从010计数到019,共10次
如果K是最高位时就不存在上述A[K]=0的情况,此时只有两种情况,如下:
1)当A[k]>1时,n=pow(10,lsize)。例如N为221时,最高位出现”1“的次数为10^2=100,也就是从100计数到199,共100次
2)当A[k]=1时,n=low+1。例如N为121时,最高位出现”1“的次数为21+1=22次,也就是从100计数到121,共22次
思路理清楚后代码就简单了,如下:
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
string N;
cin>>N;
int size=N.size(),sum=0;
for(int i=size-1;i>0;i--)
{
string temp1=N.substr(0,i);
string temp2=N.substr(i+1);
int lsize=temp2.size();
string e=temp1+temp2;
int mid=atoi(e.c_str());
int high=atoi(temp1.c_str());
int low=atoi(temp2.c_str());
if(N[i]=='1')
sum+=((high)*pow(10,lsize)+low+1);
else if(N[i]=='0')
sum+=(high*pow(10,lsize));
else
sum+=((high+1)*pow(10,lsize));
}
string t1=N.substr(1);
size=t1.size();
if(N[0]>'1')
sum+=pow(10,size);
else
{
int n=atoi(t1.c_str());
sum+=(n+1);
}
cout<<sum;
}