PAT 1049 Counting Ones (30)

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

 1 #include<iostream>
 2 #include<vector>
 3 #include<cmath>
 4 using namespace std;
 5  
 6 int main(){
 7   int n;
 8   cin>>n;
 9   int cnt=0, cpy=n;
10   vector<int> v;
11   while(cpy){//求n的每一位数
12     v.push_back(cpy%10);
13     cpy /= 10;
14   }
15   cnt = n/10;
16   if(n%10>=1) cnt++;
17   int idx=2, coe=10;
18   while(idx<=v.size()){
19     cnt += (n/(coe*10))*coe;
20     if(v[idx-1]>1)  cnt += coe;
21     else if(v[idx-1]==1) cnt += (n%coe+1);
22     coe *= 10;
23     idx++;
24   }
25   cout<<cnt;
26   return 0;
27 }

 

 

 

 
posted @ 2018-07-24 22:37  赖兴宇  阅读(137)  评论(0编辑  收藏  举报