题目链接: 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:
- 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);
}
};