俊介三

一天更新一点,一天积累一点

导航

1049. Counting Ones (30)

Posted on 2013-03-08 20:18  俊介三在前进  阅读(188)  评论(0)    收藏  举报

1049. Counting Ones (30)

http://pat.zju.edu.cn/contests/pat-a-practise/1049

输入N,输出1到N之间有多少个1。譬如,1到13之间有1,10,11,12,13 6个数字1

思路:按位数,找规律。参考

例如100

个位1的个数:它左边只能取0-9,所以有10个

十位1的个数:它左边只能取0,右边能取0-9,所以有10个

百位1的个数:1个

View Code
#include <stdio.h>

int main(){
    int d;
    scanf("%d",&d);
    int x=1;
    int total=0;
    while(d/x!=0){
        int right = d%x;
        int left = d/(x*10);
        int current = (d/x)%10;
        if(current==0) 
            total +=left*x;
        else if(current==1)
            total += left*x+right+1;
        else
            total += (left+1)*x;
        x = x*10;
    }
    printf("%d\n",total);
    return 0;
}