您的位置:首页 > 其它

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

2017-06-26 17:16 369 查看
题目

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);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: