repeatedly add all of its digits until the result has only one digit
chandra penugonda
Posted on August 12, 2023
We're provided a positive integer num. Can you write a method to repeatedly add all of its digits until the result has only one digit?
Here's an example: if the input was 49, we'd go through the following steps:
Example:
input: 49
output: 4
// start with 49
4 + 9 = 13
1+3 = 4
Solution 1
function sumDigits(num) {
function getSum(num) {
let _num = num;
let result = 0;
while (_num > 0) {
result += _num % 10;
_num = Math.floor(_num / 10);
}
return result;
}
while (num > 9) {
num = getSum(num);
}
return num
}
console.log(sumDigits(49));
Solution 2
function sumDigits(num) {
while (num > 9) {
num = num
.toString()
.split("")
.reduce((a, b) => a + parseInt(b), 0);
}
return num;
}
console.log(sumDigits(49));
💖 💪 🙅 🚩
chandra penugonda
Posted on August 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.