Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Follow up: Could you do it without any loop/recursion in O(1) runtime?
Solution 1
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
"use strict";
let sum = num;
while (sum >= 10) {
num = sum;
sum = 0;
while (num) {
sum += num % 10;
num = Math.floor(num/10);
}
}
return sum;
};
Solution 2
/**
* Solved with congruence formula
* https://en.wikipedia.org/wiki/Digital_root#Congruence_formula
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
"use strict";
return 1 + (num-1) % 9;
};