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
特别经典的算法,借鉴学习了
#include <iostream> #include <map> #include <queue> #include <stdio.h> #include <vector> #include <algorithm> #include <stack> #include <stdlib.h> #include <string.h> #include <math.h> #include <string> using namespace std; int c,base; int main() { int n; while(scanf("%d",&n)!=EOF){ c=0;base=1; while(n/base!=0){ int low=n%base; //当前权值的低位 int high=(n/base)/10; //当前权值的高位 int now=(n/base)%10; //当前权值位 if(now==0) c+=high*base; else if(now==1) c+=high*base+low+1; else c+=(high+1)*base; base*=10; //注意 } printf("%d ",c); } return 0; }