标签:
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)
2001-2999 -> 递归(999)
.
.
8000-8192 -> 递归(192)
总数是:递归(999)*8 + 1000 + 递归(192)
要注意到如果是1192
总数是:递归(999)*1 + (1000 - 192 + 1) + 递归(192)
(1000 - 192 + 1)是1000-1192中千位上的1。
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 };
[LeetCode][JavaScript]Number of Digit One
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4631726.html