Given an integer num
, repeatedly add all its digits until the result has only one digit, and return it.
Example
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Solution
/**
* @param {number} num
* @return {number}
*/
var addDigits = function (num) {
//While loop to run until number is less than 10
while (num > 9) {
//Set to string, split, reduce, and parse
num = num
.toString()
.split("")
.reduce((a, b) => parseInt(a) + parseInt(b));
}
return num;
};