# [LeetCode] 233. Number of Digit One 数字1的个数

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

Example 1:

Input: n = 13
Output: 6


Example 2:

Input: n = 0
Output: 0


Constraints:

• 0 <= n <= 2 * 109

1的个数          含1的数字                                                                        数字范围

1                   1                                                                                     [1, 9]

11                 111  111111119                              [10, 19]

1                   21                                                                                   [20, 29]

1                   31                                                                                   [30, 39]

1                   41                                                                                   [40, 49]

1                   51                                                                                   [50, 59]

1                   61                                                                                   [60, 69]

1                   71                                                                                   [70, 79]

1                   8                                                                                  [80, 89]

1                   91                                                                                   [90, 99]

11                 100  101  102  103  104  105  106  107  108  109          [100, 109]

21                 11111  11111111111111119             [110, 119]

11                 120  121  122  123  124  125  126  127  128  129          [120, 129]

...                  ...                                                                                  ...

class Solution {
public:
int countDigitOne(int n) {
int res = 0, a = 1, b = 1;
while (n > 0) {
res += (n + 8) / 10 * a + (n % 10 == 1) * b;
b += n % 10 * a;
a *= 10;
n /= 10;
}
return res;
}
};

class Solution {
public:
int countDigitOne(int n) {
int res = 0;
for (long k = 1; k <= n; k *= 10) {
long r = n / k, m = n % k;
res += (r + 8) / 10 * k + (r % 10 == 1 ? m + 1 : 0);
}
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/233

Factorial Trailing Zeroes

Digit Count in Range

https://leetcode.com/problems/number-of-digit-one/

https://leetcode.com/problems/number-of-digit-one/discuss/64390/AC-short-Java-solution

https://leetcode.com/problems/number-of-digit-one/discuss/64381/4+-lines-O(log-n)-C++JavaPython

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2015-07-08 02:50  Grandyang  阅读(18773)  评论(5编辑  收藏  举报