【PAT】1049. Counting Ones (30)

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出現的個數。 根據《編程之美》書上的 “2.4 1的數目” 寫的。代碼如下:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int sum(int n){
	int iCount = 0;
	int iFractor = 1;
	int iLowerNum = 0;
	int iCurrNum = 0;
	int iHigherNum = 0;
	while(n/iFractor != 0){
		iLowerNum = n-(n/iFractor)*iFractor;
		iCurrNum = (n/iFractor)%10;
		iHigherNum = n / (iFractor*10);
		switch(iCurrNum){
			case 0:
				iCount += iHigherNum*iFractor;
				break;
			case 1:
				iCount += iHigherNum*iFractor + iLowerNum + 1;
				break;
			default:
				iCount += (iHigherNum + 1) * iFractor;
				break;
		}
		iFractor *= 10;
	}
	return iCount;
}

int main(int argc, char** argv) {
	int n;
	scanf("%d",&n);
	printf("%d\n",sum(n));
	return 0;
}


發佈了142 篇原創文章 · 獲贊 13 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章