美文网首页一起来刷算法题
整数中1出现的次数(从1到n整数中1出现的次数)

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

作者: cherryleechen | 来源:发表于2019-05-06 21:31 被阅读0次

时间限制:1秒 空间限制:32768K

题目描述

求出任意非负整数区间中1出现的次数(从1到n中1出现的次数)。

我的代码

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        /*若要计算百位上1出现的次数,
        它受到了3方面的影响:百位上的数字、百位以下低位上的数字、百位以上高位上的数字。
        当百位上数字是0时,受高位数字影响;
        当百位上数字是1时,受高位和低位数字影响;
        当百位上的数字是2-9时,受高位数字影响。*/
        if(n<0)
            throw n;
        int i=1,res=0;
        int cur=0,low=0,high=0;
        while(n/i){
            cur=(n/i)%10;
            low=n-i*(n/i);
            high=(n/i)/10;
            if(cur==0)
                res+=high*i;
            else if(cur==1)
                res+=high*i+low+1;
            else
                res+=(high+1)*i;
            i*=10;
        }
        return res;
    }
};

运行时间:3ms
占用内存:472k

相关文章

网友评论

    本文标题:整数中1出现的次数(从1到n整数中1出现的次数)

    本文链接:https://www.haomeiwen.com/subject/nyytoqtx.html