1的数量(51nod)

来源:互联网 发布:易通网络加速器官网 编辑:程序博客网 时间:2024/06/08 13:43

求1-n中出现1的数量。
《编程之美》该书中提到过这题的解法
假设n=abcde,
如果百位上的数字为0,那么,百位上出现1的次数由更高位决定,例如:12013,百位上出现1的情况为,1-199,1100-1199,2100-2199,…,11100~11199,一共有12*100个
如果百位上的数字为1,那么,百位上出现1的次数由高位和低位的数影响,例如:12113,高位1-199,1100-1199,2100-2199,…,11100~11199,一共有12*100个,低位12100~12113,一共113+1个
如果百位上的数字大于1,则百位上可能出现1的次数由更高位决定,例如12213,1-199,1100-1199,2100-2199,…,11100~11199, 12100~12199 共(12+1)*100

#include <cstdio>int read(){int ret=0;char ch=getchar();while(ch<'0'||ch>'9') ch=getchar();for(;ch>='0'&&ch<='9';ch=getchar()) ret=ret*10+ch-'0';return ret;}int main(){    int n=read();    int pos=1,ans=0;    while(n/pos)    {        int low=n-(n/pos)*pos;        int now=(n/pos)%10;        int high=n/(pos*10);        if(now==0)            ans+=high*pos;        else if(now==1)            ans+=high*pos+low+1;        else            ans+=(high+1)*pos;        pos*=10;    }    printf("%d\n",ans);}
0 0
原创粉丝点击