[LeetCode][JavaScript]Number of Digit One
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.
数学题,真是为难了数学拙计的我了。
递归分治,每一轮递归都会减少一位,拿8192举栗子:
把8192拆成:
1-999 -> 递归(999)
1000-1999 -> 1000个1 + 递归(999)
2000-2999 -> 递归(999)
.
.
7000-7999 -> 递归(999)
8000-8192 -> 递归(192)
总数是:递归(999)*8 + 1000 + 递归(192)
要注意到如果是1192
总数是:递归(999)*1 + (1000 - 192 + 1) + 递归(192)
(1000 - 192 + 1)是1000-1192中千分位上的1。
https://leetcode.com/discuss/44496/5lins-solution-using-recursion
The concept is count 1s in current level, recursively do it until the number is smaller than 10.
For example '8192':
1-999 -> countDigitOne(999)
1000-1999 -> 1000 of 1s + countDigitOne(999)
2000-2999 -> countDigitOne(999)
.
.
7000-7999 -> countDigitOne(999)
8000-8192 -> countDigitOne(192)
Count of 1s : **countDigitOne(999)*8 + 1000 + countDigitOne(192)**
**Noticed that**, if the target is '1192':
Count of 1s : **countDigitOne(999)*1 + (1192 - 1000 + 1) + countDigitOne(192)**
(1192 - 1000 + 1) is the 1s in thousands from 1000 to 1192.
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var countDigitOne = function(n) { 6 if(n <= 0){ 7 return 0; 8 }else if(n < 10){ 9 return 1; 10 } 11 var len = n.toString().length; 12 var base = Math.pow(10, len - 1); 13 var answer = parseInt(n / base); 14 var remainder = n % base; 15 var oneInBase = 0; 16 if(answer === 1){ 17 oneInBase = n - base + 1; 18 }else{ 19 oneInBase = base; 20 } 21 return countDigitOne(base - 1) * answer + oneInBase + countDigitOne(remainder); 22 };
然后少开几个变量,强行把代码写在一行上,在实际项目中不要这么做哦,过段时间自己也读不懂了。
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var countDigitOne = function(n) { 6 if(n <= 0) return 0; 7 if(n < 10) return 1; 8 var base = Math.pow(10, n.toString().length - 1); 9 var answer = parseInt(n / base); 10 return countDigitOne(base - 1) * answer + (answer === 1 ? (n - base + 1) : base) + countDigitOne(n % base); 11 };