【PAT】1049. Counting Ones (30)

来源:互联网 发布:mac版ps烟雾笔刷下载 编辑:程序博客网 时间:2024/06/05 18:57

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;}


0 0
原创粉丝点击