码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1049 Counting Ones (30)

时间:2018-07-24 23:51:17      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:code   copy   +=   观察   form   output   test   lin   put   

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;
}

 

 

PAT 1049 Counting Ones (30)

标签:code   copy   +=   观察   form   output   test   lin   put   

原文地址:https://www.cnblogs.com/mr-stn/p/9363120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!