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 (<=2^30^).
Output Specification:
For each test case, print the number of 1‘s in one line.
Sample Input:
12
Sample Output:
5
#include<iostream> #include<vector> using namespace std; int main(){ int n; while(1){ cin>>n; if(n==-1) break; vector<int> v; v.push_back(0); for(int i=1; i<=n; i++){ int cnt=0, temp=i; while(temp){ if(temp%10==1) cnt++; temp/=10; } v.push_back(v[i-1]+cnt); } cout<<v[n]<<" "<<f(n)<<endl; } return 0; }
观察可以发现每一位1出现的次数和当前位左边的数有关 也和右边的数有关;
计算1的个数还与当前为的数有关
当前位为0的时候
当前位为1
当前位为12..9
#include<iostream> using namespace std; int ceil(int num1, int num2){ return num1%num2==0 ? num1/num2 : num1/num2+1; } int main(){ int n, copy, i; cin>>n; copy=n/10; int coe=10, ans = ceil(n, 10); while(copy>9){ int dig=copy%10, up=ceil(n, coe*10); if(dig==1) ans += ((up-1)*coe+n%coe+1); else if(dig>1) ans += up*coe; else if(dig==0) ans += (n/(10*coe)*coe + (n%coe/coe>=1?1:0)); coe*=10; copy/=10; } if(copy>1) ans += coe; else if(copy==1) ans += ((n%coe)+1); cout<<ans<<endl; return 0; }