从1到n整数中1出现的次数

#include<stdio.h>

long long int Count(long long int n){
    //1的个数
    long long int count = 0;
    //当前位
    long long int Factor = 1;
    //低位数字
    long long int LowerNum = 0;
    //当前位数字
    long long int CurrNum = 0;
    //高位数字
    long long int HigherNum = 0;
    if(n <= 0){
        return 0;
    }
    while(n / Factor != 0){
        //低位数字
        LowerNum = n - (n / Factor) * Factor;
        //当前位数字
        CurrNum = (n / Factor) % 10;
        //高位数字
        HigherNum = n / (Factor * 10);
        //如果为0,出现1的次数由高位决定
        if(CurrNum == 0){
            //等于高位数字 * 当前位数
            count += HigherNum * Factor;
        }
        //如果为1,出现1的次数由高位和低位决定
        else if(CurrNum == 1){
            //高位数字 * 当前位数 + 低位数字 + 1
            count += HigherNum * Factor + LowerNum + 1;
        }
        //如果大于1,出现1的次数由高位决定
        else{
            //(高位数字+1)* 当前位数
            count += (HigherNum + 1) * Factor;
        }
        //前移一位
        Factor *= 10;
    }
    return count;
}

int main(){
    long long int a;
    while(scanf("%lld",&a) != EOF){
        printf("%lld\n",Count(a));
    }
    return 0;
}

http://blog.csdn.net/sjf0115/article/details/8600599

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值