leetcode+计算从1到n的包含1的个数

https://leetcode.com/problems/number-of-digit-one/description/

//从1到n包含的1的个数
public:
    int countDigitOne(int n) {
        int res = 0;
        int left=0, right = 0, base = 1;
        if(n<=0) return 0;
        while (n>=base) {
            left = n/base;
            right = n%base;
            if((left%10)>1) res+= (left/10+1)*base;
            else if((left%10)==1) res+=(left/10)*base+(right+1);
            else res+=(left/10)*base;
            base *=10;
        }
        return res;
    }
};

leetcode+计算从1到n的包含1的个数_第1张图片

你可能感兴趣的:(Leetcode)