233. 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.
鏈接:?http://leetcode.com/problems/number-of-digit-one/
題解:
又是數學題,主要思路是用遞歸來做。還有一些別的解法,二刷的時候爭取理解最優解。
下面我們來一步步分析:
Time Complexity ?- O(log10n), Space Complexity - O(log10n)
public class Solution {public int countDigitOne(int n) {if (n < 1)return 0;if (n < 10)return 1;int baseInTen = (int)Math.pow(10, String.valueOf(n).length() - 1); int highestDigit = n / baseInTen; // get the highest digit of nif(highestDigit == 1)return countDigitOne(baseInTen - 1) + (n - baseInTen + 1) + countDigitOne(n % baseInTen);elsereturn highestDigit * 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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS开发--一些UITabBarIte
- 下一篇: doctype声明的意义