您的位置:首页 > 其它

【PAT】1049. Counting Ones (30)

2015-11-04 20:28 471 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT