zoukankan      html  css  js  c++  java
  • 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 }
     
     
  • 相关阅读:
    洛谷P3620 [APIO/CTSC 2007] 数据备份
    洛谷P2744 量取牛奶
    洛谷P1560 蜗牛的旅行
    luogu P1776 宝物筛选_NOI导刊2010提高(02)
    luogu P1020 导弹拦截
    luogu P2015 二叉苹果树
    luogu P1137 旅行计划
    树形dp瞎讲+树形dp基础题题解
    luogu P1252 马拉松接力赛 P1803 凌乱的yyy / 线段覆盖
    luogu P1196 [NOI2002]银河英雄传说
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9363120.html
Copyright © 2011-2022 走看看