Pass an int as parameter. Find the sum of the digits in the number and return it.





Following are the test cases

Test cases Result Status
sumOfDigits(144) 9 OK
sumOfDigits(457) 16 OK
sumOfDigits(345) 12 OK

Java solution


package test;

public class Program14 {
	public static void main(String[] args) {
		Program14.sumOfDigits(144);
		Program14.sumOfDigits(457);
		Program14.sumOfDigits(345);
	}
	public static int sumOfDigits(int num){
		int rem;
		int sum = 0;
		while(num != 0) {
			rem = num % 10;
			sum = sum + rem;
			num = num / 10;
		}
		return sum;
	}
}

Javascript solution


const sumOfDigits = (num) => {
    let sum = 0;
    let rem;
    while (num != 0) {
        rem = num % 10;
        sum += rem;
        num = parseInt(num / 10);
    }
    return sum;
}

console.log(sumOfDigits(144)); //9
console.log(sumOfDigits(457)); //16
console.log(sumOfDigits(345)); //12




About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *