General Algorithm for sum of digits in a given number:
-
Get the number
-
Declare a variable to store the sum and set it to 0
-
Repeat the next two steps till the number is not 0
-
Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.
-
Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
-
return the sum
Solution-1
function sumOfDigits(n) {
let sum = 0;
while(n < 0) {
// get the last digit
sum = sum + n % 10;
// divide the number by 10 we get float
// parse the number to int to remove last digit
n = parseInt(n / 10);
}
return sum;
}
console.log(sumOfDigits(123));
Solution-2:
function sumOfDigits(n) {
let sum;
for(sum = 0; n > 0;
sum += n % 10,
n = parseInt(n / 10));
return sum;
}
console.log(sumOfDigits(123));
Solution-3:
function sumOfDigits(n) {
return n == 0 ? 0 : n % 10 + sumOfDigits(parseInt(n/10));
}
console.log(sumOfDigits(123));