LeetCode233,数字1的个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jeff_Winger/article/details/82694815

规律如下:

如果第 i (自右向左,从1开始标号)上的数字是0,则第 i 位可能出现 1 的次数由更高位决定(若没有高位,则高位为0),等于更高位数乘以当前位数的权重(10i-1)

如果第 i 位上的数字为 1,则第 i 位上出现 1 的次数不仅受更高位影响,还受低位影响(若没有低位,则低位为0),等于更高位数乘以当前位数的权重 (10i-1) + (低位数 + 1)

如果第 i 位上的数字大于 1,则第 i 位上可能出现 1 的次数仅由更高位决定(若没有高位,则高位为0),等于(更高位数 + 1)乘以当前位数的权重 (10i-1)

总结:当前位的个数=     {\begin{cases} higher*{10_{}}^{i-1}& \text{ if } i<1 \\ higher*{10_{}}^{i-1}+lower+1 & \text{ if } i= 1\\ (higher+1)*{10_{}}^{i-1}& \text{ if } i>1 \end{cases}}{}

代码如下:

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int count=0;
        int high=n;
        int cur=0,b=1;
        while(high>0)
        {
            cur=high%10;
            high/=10;
            count+=high*b;
            if(cur==1){
                count+=n%b+1;
            }else if(cur>1){
                count+=b;
            }
            b*=10;
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/Jeff_Winger/article/details/82694815