ADD Digits
Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since have only one 2
digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Hint:
- A naive implementation of the above process is trivial. Could come up with other methods?
- What is all the possible results?
- How does they occur, periodically or randomly?
- You could find this Wikipedia article useful.
The maths problem is kneeling.
If you can use loops, the best case is to read the numbers, O (1) Time complexity.
Greedy, each read a number to do digit root operation, the final result is correct.
1 /**2 * @param {number} num3 * @return {number}4 */5 varAdddigits =function(num) {6 varstr = num.tostring (), res = 0, TMP1, TMP2;7 for(vari = 0; i < str.length; i++){8res = parseint (Str[i]) +Res;9 if(Res >= 10){TenTMP1 = parseint (RES/10); OneTMP2 = res% 10; Ares = TMP1 +TMP2; - } - } the returnRes; -};
Best Answer Reference Wiki:https://en.wikipedia.org/wiki/digital_root
There are several ways to do this, and there are 2 of them listed here.
1 /* 2 * @param {number} num 3 * @return {number} 4 */ 5 var adddigits = function 6 return num = = 0? 0:num-9 * Math.floor ((num-1)/9 7 };
1 /* * 2 * @param {number} num 3 * @return {number} 4 */ 5 var function (num) {6 return 1 + (num-1)% 9; 7 };
[Leetcode] [JavaScript] ADD Digits