Leetcode 233. 数字1的个数

版权声明:转载请注明 https://blog.csdn.net/qq_33831360/article/details/88754466

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

示例:

输入: 13
输出: 6 
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。

题很简单,但lc的数据赶上 cf了,又是炸int,又是<0,WA的一声哭了

思路就是统计每一位:

这一位是2-9,如23(3)33中3前面可以是0-23,后面是0-99,共有24*100种

这一位是0,不统计

这一位是1,如23(1)33,前面仍是0-23,后面是0-33

class Solution {
public:
    int countDigitOne(int n) {
        if (n < 0) return 0;
        long long ans = 0,val = 1,rel = 0;
        while (n) {
            ans += (n/10)*val;
            if(n%10 == 1) ans += rel+1;
            else if (n%10) ans += val;
            rel = rel+val*(n%10);
            val *= 10;
            n /= 10;
        }
        return ans;
        
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33831360/article/details/88754466
今日推荐