PAT-A-1049-Counting Ones

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:

1
12

Sample Output:

1
5

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

int main(){
int n,a=1,ans=0;
//从低位到高位遍历一个数,将其分为left now right三个部分,并讨论now=0、1、大于1三种情况下的结果
int left,now,right;
scanf("%d",&n);

//从低位到高位遍历每个数
while(n/a!=0){
left = n/(a*10);
now = n/a%10;
//任何数取余1都为0
right = n%a;
if(now==0)
ans+=left*a;
else if(now==1)
ans+=left*a+right+1;
else
ans+=(left+1)*a;
a*=10;
}

printf("%d",ans);

return 0;
}

----\(˙<>˙)/----赞赏一下吧~