【PAT】A1049. Counting Ones (30)

Description:
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

//NKW 甲级真题1038
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
int main(){
	int num, cnt = 0, a = 1, left, now, right;
	scanf("%d", &num);
	while (num/a){
		left = num / (a * 10);
		now = num / a % 10;
		right = num % a;
		if (now == 0)		//0xxx
			cnt += left * a;
		else if (now == 1)	//1xxx,1000、1001……1xxx
			cnt += left*a + right + 1;
		else				//2xxx,1000、1001……1999
			cnt += (left + 1)*a;
		a *= 10;
	}
	printf("%d\n", cnt);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ztmajor/article/details/81088345