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


搞清思路:设某位为1,在这种条件下,统计不大于给定数的这种数的个数,从个位依次向最高位拓展

#include
#include
#include
#include
#include
using namespace std;
/*
	暴力求解:O(nlogn) n=2^30=10^9 超时
	考虑当前位置出现1
	如果当前位==0,则该位出现1 的情况由更高位决定,= 更高位数字*当前位数
	如果当前位==1,则该位出现1 的情况受更高位以及低位影响,= (更高位数字*当前位数)+(低位数字+1)
	如果当前位>1,则该为出现1 的情况由更高位决定,= (更高为数字+1)*当前位数

	eg:针对百位出现1
	203	010-019 110-119 2*10
	213 010-019 110-119 210-213 2*10+3+1
	223 010-019 110-119 210-219 (2+1)*10

	分解为[left]cur[right]
*/
int main()
{
	int d,weight=1,total=0;
	int left,right,cur;
	cin>>d;
	do{
		right=d%weight;
		cur=d/weight %10;
		left=d/(weight*10);
		if(cur==0)	total+=left*weight;
		else if(cur==1)	total+=left*weight+right+1;
		else total+=(left+1)*weight;
		weight*=10;
	}while(cur!=0);
	cout<

你可能感兴趣的:(1049. Counting Ones)