天天看点

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 (≤2^​30).

Output Specification:

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

Sample Input:

12

Sample Output:

5

思路

思路来源于别人的博客https://blog.csdn.net/CV_Jason/article/details/85112495

简要概括一下,计算某一位出现1的次数,就是把原数该位置为1,计算其左边数和右边数有多少种组合情况,使得到的数小于等于原数。

AC代码

#include <iostream>
using namespace std;

int main(){
	int n, sum = 0;
	cin>>n;
	int now, left, right, a = 1;
	while(n / a){
		now = (n / a) % 10;
		left = n / (a * 10);
		right = n % a;
		if(now == 0) sum += left * a;
		else if(now == 1) sum += left * a + right + 1;
		else sum += (left + 1) * a;
		a *= 10;
	}
	cout<<sum;
	return 0;
}