剑指offer 43. 1~n 整数中 1 出现的次数

剑指offer 43. 1~n 整数中 1 出现的次数

题目描述

在这里插入图片描述

解题思路

参考题解:面试题43. 1~n 整数中 1 出现的次数(清晰图解)
在这里插入图片描述
时间:o(logn),空间:o(1)

class Solution {
    
    
    public int countDigitOne(int n) {
    
    
        //将 n 划分为 high、cur、low 三部分,以及 cur 当前所在的数位,初始化从个位开始
        int low = 0, cur = n % 10, high = n / 10, digit = 1;
        int res = 0;
        //遍历条件为 high 和 cur 不为0,low 表示已经遍历过的部分
        while (high != 0 || cur != 0) {
    
    
            if (cur == 0) {
    
    
                res += high * digit;
            } else if (cur == 1) {
    
    
                res += high * digit + low + 1;
            } else {
    
    
                res += (high + 1) * digit;
            }
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115280688