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

46 篇文章 0 订阅

题目链接: https://leetcode.com/problems/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.

Hint:

  1. Beware of overflow.

思路: 可以找出一些规律, 

1. 在n = 9时, 只有一个1

2. 在n = 99时, 个位所有数字会出现十次, 因此在个位上会出现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,设k 为与n位数相同的最小值,即如10, 100, 1000.... sum = n/10 * count(k-1) + k + count(n%k);
2. 如果n的最高位 =1,设k 为与n位数相同的最小值,即如10, 100, 1000.... sum = count(k-1) + n%k + count(n%k);

其原则就是从最高位向低位递归的处理.

代码如下:

class Solution {
public:
    int countDigitOne(int n) {
        if(n <= 0) return 0;
        if(n <= 9) return 1;
        int len = to_string(n).size(), num = pow(10, len-1);
        if(n >= 2*num) return num+countDigitOne(n%num)+n/num*countDigitOne(num-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、付费专栏及课程。

余额充值