Collapse Digits
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
Write your solution:
Test Case 1
Input: 38
Output: 2
Test Case 2
Input: 103
Output: 4
Test Case 3
Input: 987
Output: 6
Solution
function collapseDigits(num) {
return 1 + ((num - 1) % 9);
}
Solution
function collapseDigits(num) {
const result = String(num)
.split('')
.reduce((acc, cur) => acc + Number(cur), 0);
if (result < 10) {
return result;
}
return collapseDigits(result);
}