整数中1出现的次数(从1到n整数中1出现的次数)

2020-07-28  本文已影响0人  Crazy_Bear
class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        if(n<1) return 0;
        int count = 0;
        int base = 1;
        int round = n;
        while(round>0){
            int weight = round%10;
            round /= 10;
            count += round * base;
            if(weight == 1) count += (n%base + 1)  ;
            else if(weight > 1) count+=base;
            base *=10;
        }
        return count;
    }
};
上一篇下一篇

猜你喜欢

热点阅读