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:12Sample 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;
}