cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/92e3e5a7df5d

时间限制: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

posted on 2019-05-06 21:32  cherrychenlee  阅读(90)  评论(0编辑  收藏  举报