zoukankan      html  css  js  c++  java
  • 数1的个数

    总时间限制: 
    1000ms
     
    内存限制: 
    65536kB
    描述

    给定一个十进制正整数n,写下从1到n的所有整数,然后数一下其中出现的数字“1”的个数。

    例如当n=2时,写下1,2。这样只出现了1个“1”;当n=12时,写下1,2,3,4,5,6,7,8,9,10,11,12。这样出现了5个“1”。

    输入
    正整数n。1 <= n <= 10000。
    输出
    一个正整数,即“1”的个数。
    样例输入
    12
    样例输出
    5
    来源
    习题(8-11) 医学部 2010 期末试题 尤朝

    代碼實現:

     1 #include<cstdio>
     2 int n,ans;
     3 int main(){
     4     scanf("%d",&n);
     5     for(int i=1;i<=n;i++){
     6         if(i%10==1) ans++;
     7         if(i%100/10==1) ans++;
     8         if(i%1000/100==1) ans++;
     9         if(i%10000/1000==1) ans++;
    10         if(i/10000==1) ans++;
    11     }
    12     printf("%d
    ",ans);
    13     return 0;
    14 }

    。。。

    大数优化版:

     1 #include<cstdio>
     2 int n,a=1,ans;
     3 int main(){
     4     scanf("%d",&n);
     5     while(n>=a){
     6         ans+=n/(10*a)*a;
     7         if(n/a%10>1) ans+=a;
     8         if(n/a%10==1) ans+=n%a+1;
     9         a*=10;
    10     }
    11     printf("%d
    ",ans);
    12     return 0;
    13 }

    这个规律应该是显而易见的。

  • 相关阅读:
    zoj1137 poj1466
    poj3041
    zoj1455
    hdu1160 FatMouse's Speed
    zoj2770
    hdu1469
    hdu3169
    Mapped exception to response: 500 (Internal Server Error)
    Mapped exception to response: 500 (Internal Server Error)
    object is not a function
  • 原文地址:https://www.cnblogs.com/J-william/p/6156174.html
Copyright © 2011-2022 走看看