Topic:
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.
Links: http://leetcode.com/problems/number-of-digit-one/
Exercises
is a mathematical problem, the main idea is to do it by hand. There are some other solutions, two brushes to understand the best solution.
Let's step through the analysis:
- N < 1 o'clock with a result of 0
- 1 <= N < 10 o'clock with a result of 1
Assuming n = 312, we break this calculation process down into several steps:
- (1 ~ 99) with a result of Countdigitone (99)
- (100 ~ 199), result is + countdigitone (99)
- (200 ~ 299) with a result of Countdigitone (99)
- (300 ~ 312) with a result of Countdigitone (12)
- Assuming n = 112, we also decompose this calculation process:
- (1 ~ 99) with a result of Countdigitone (99)
- (100 ~ 112), result 112-100 + 1 + countdigitone (12)
- As a result, we can introduce the general formula
Time Complexity-o (log10n), Space complexity-o (log10n)
Public classSolution { Public intCountdigitone (intN) {if(N < 1) return0; if(N < 10) return1; intBaseinten = (int) Math.pow (string.valueof (n). Length ()-1); intHighestdigit = N/baseinten;//get the highest digit of n if(Highestdigit = = 1) returnCountdigitone (baseInTen-1) + (N-baseinten + 1) + countdigitone (n%Baseinten); Else returnHighestdigit * Countdigitone (baseInTen-1) + Baseinten + countdigitone (n%Baseinten); }}
Reference:
Https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python
Https://leetcode.com/discuss/44279/clean-c-code-of-log10-complexity-with-detailed-explanation
Https://leetcode.com/discuss/44314/accepted-solution-using-counting-principle-with-explanation
Https://leetcode.com/discuss/44465/my-ac-java-solution-with-explanation
Https://leetcode.com/discuss/44617/my-recursion-implementation
Https://leetcode.com/discuss/47774/0ms-recursive-solution-in-c-8-line-code
Https://leetcode.com/discuss/46366/ac-short-java-solution
Https://leetcode.com/discuss/64604/my-simple-and-understandable-java-solution
Https://leetcode.com/discuss/64962/java-python-one-pass-solution-easy-to-understand
Https://leetcode.com/discuss/54107/0-ms-recursive-solution
Https://leetcode.com/discuss/58868/easy-understand-java-solution-with-detailed-explaination
233. Number of Digit One