A1049 Counting Ones (30 point(s))

数论

1. 原文

原题

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 (≤$2^{30}$).

output Specification:

For each test case, print the number of 1’s in one line.

Sample Input:

1
12

Sample output:

1
5

2. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<cstdio>
int main()
{
int n;
scanf("%d",&n);
int a=1;
int ans=0;
while(n/a){
int left=n/(a*10);
int now=n/a%10;
int 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\n",ans);
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1049/
  • 发布时间: 2019-09-03 12:34
  • 更新时间: 2021-10-29 14:01
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!