剑指offer面试题43:1~n整数中1出现的次数(思路要复习)

这道题我一开始的想法是,把数字按位数分开,比如19872分成10000和10001-19872,然后对于10的幂次方的值打表,找规律,但后来发现,这样分开,涉及到的很多琐碎的加一要考虑(就是10001-19872和10000-19872的区别,每一次这样分开,都要加一,就会加多,只加一次,一些数据又不需要加一,很难办),最后看了答案,答案直接按位找规律计算,不用递归分开,省事很多。(https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/

答案讲解的很清晰,不多写了

    public int countDigitOne(int n) {
        int high = n/10,cur = n%10,low = 0;
        int digit = 1;
        int res=0;
        while(high!=0||cur!=0){
            if(cur == 0){
                res += high*digit;
            }else if(cur == 1){
                res+= (high*digit + low+1);
            }else{
                res += high*digit + digit;
            }
            low +=(cur*digit);
            cur = high%10;
            high/=10;
            
            digit*=10;
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/114436086