[Leetcode] 233. Number of Digit One 解题报告

题目

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

思路

这是一道总结规律的题目:

1. 在n = 9 时, 只有一个1;
2. 在n = 99 时, 个位所有数字会出现10次, 因此在个位上会出现10次1, 而在十位上只会出现10次1, 就是在10-19的时候, 因此n =99 时1出现的次数为 10*1 + 10 = 20;
3. 在n = 999 时, 相当于包含了10次n=99, 并且在百位上会出现100次1, 就是100-199, 因此当n=999 时1出现的次数为10*20 + 100 = 300;
4, 在n = 9999 时, 相当于包含了10次n=999, 并且在千位上会出现1000次1, 就是在1000-1999, 因此当n=9999 时1出现的次数为10*300 + 1000 = 4000。

因此我们可以看到规律就是:
1. 如果n的最高位 > 1,设num 为与n位数相同的最小值,即如10, 100, 1000.... sum = num + count(n%num) + n/num * count(num-1);
2. 如果n的最高位 = 1,设num 为与n位数相同的最小值,即如10, 100, 1000.... sum = n%num + 1 + count(n%num) + count(num-1)。

这道题目除了考查逻辑和数学能力之外,似乎没有任何算法方面技巧(递归除外),据说现在面试已经不太喜欢考这种类型的题目了。

代码

class Solution {
public:
    int countDigitOne(int n) {
        if (n <= 0) {
            return 0;
        }
        if (n <= 9) {
            return 1;
        }
        int length = to_string(n).size();
        int num = pow(10, length - 1);
        if (n >= 2 * num) {     // the digit in the highest bit is larger than 1
            return num + countDigitOne(n % num) + n / num * countDigitOne(num - 1);
        }
        else {                  // the digit in the hightest bit is 1
            return n % num + 1 + countDigitOne(n % num) + countDigitOne(num - 1);
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值