1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
2015-12-06 21:25
489 查看
题目信息
1049. Counting Ones (30)时间限制10 ms
内存限制65536 kB
代码长度限制16000 B
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:
12
Sample Output:
5
解题思路
《编程之美》中计算0到N包含数字1的个数问题AC代码
#include <cstdio> int get(long long n){ long long cur = 0, before = 0, after = 0, i = 1, cnt = 0; while ((n / i) != 0){ cur = n / i % 10; before = n / i / 10; after = n - (n / i) * i; if (cur == 0){ cnt += before * i; }else if (cur == 1){ cnt += before * i + after + 1; }else { cnt += (before + 1) * i; } i *= 10; } return cnt; } int main() { long long a; scanf("%lld", &a); printf("%d\n", get(a)); return 0; }
相关文章推荐
- libdvbpsi源码分析(四)PAT表解析/重建
- PAT配置
- 什么是端口复用动态地址转换(PAT) 介绍配置实例
- MikroTik layer7-protocol
- PAT是如何工作的
- PAT 乙级题:1002. 写出这个数 (20)
- PAT (Advanced Level) Practise 1001-1010
- 数据结构学习与实验指导(一)
- PAT Basic Level 1001-1010解题报告
- 1001. 害死人不偿命的(3n+1)猜想
- 1002. 写出这个数
- 1032. 挖掘机技术哪家强
- 1001. 害死人不偿命的(3n+1)猜想 (PAT basic)
- 1002. 写出这个数(PAT Basic)
- 1004. 成绩排名(PAT Basic)
- 1006. 换个格式输出整数(PAT Basic)
- 1007. 素数对猜想(PAT Basic)
- 1008. 数组元素循环右移问题
- 1009. 说反话(PAT Basic)
- 1011. A+B和C(PAT Basic)