Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 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

12

Sample Output

5

解答

#include <cstdio>

int main()
{
	long long n, cnt = 0; scanf("%lld", &n);
	for (long long q = 1; q <= n; q *= 10)
	{
		int d = n / q % 10;
		if (d > 1) cnt += (1 + n/q/10) * q;
		else if(d == 1) cnt += n/q/10 * q + n%q + 1;
		else cnt += n/q/10 * q;
	}
	printf("%d\n", cnt);
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论