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.
Maths problem, it's really embarrassing for me to be a math clumsy.
Recursive division, take 8192 to raise chestnuts:
Split the 8192 into:
1-999, recursion (999)
1000-1999-1000 1 + recursion (999)
2001-2999, recursion (999)
.
.
8000-8192, recursion (192)
Total is: recursive (999) *8 + 1000 + recursive (192)
Notice that if it's 1192,
Total: Recursive (999) * + (1000-192 + 1) + recursive (192)
(1000-192 + 1) is 1 of the thousands on the 1000-1192.
1 /**2 * @param {number} n3 * @return {number}4 */5 varCountdigitone =function(n) {6 if(n <= 0){7 return0;8}Else if(N < 10){9 return1;Ten } One varLen =n.tostring (). length; A varBase = Math.pow (Ten, len-1); - varAnswer = parseint (N/base); - varremainder = n%Base; the varOneinbase = 0; - if(Answer = = 1){ -Oneinbase = n-base + 1; -}Else{ +Oneinbase =Base; - } + returnCountdigitone (base-1) * answer + oneinbase +countdigitone (remainder); A};
Then less open a few variables, forced to write code on one line, in the actual project do not do so oh, after a period of time you can not understand.
1 /**2 * @param {number} n3 * @return {number}4 */5 varCountdigitone =function(n) {6 if(n <= 0)return0;7 if(N < 10)return1;8 varBase = Math.pow (Ten, N.tostring (). length-1);9 varAnswer = parseint (N/base);Ten returnCountdigitone (base-1) * answer + (answer = = = 1?) (N-base + 1): Base) + countdigitone (n%base); One};
[Leetcode] [JavaScript] Number of Digit One