Search⌘ K
AI Features

Solution Review: Sum of Digits in an Integer

Explore how to write a Java method that calculates the sum of digits in an integer. Understand using a while loop, extracting digits with modulus and division, accumulating results, and returning the final sum.

We'll cover the following...

Solution

Java
class SumDigits {
public static int sumOfDig(int var) {
int result = 0; //variable for resultant sum
int lastDigit = 0;
while (var > 0) {
//seclude & keep adding the last digit into result
lastDigit = var % 10;
result = result + lastDigit;
System.out.println("Last Digit: " + lastDigit);
System.out.println("Sum: " + result);
var /= 10; //update the new value of var
System.out.println("Number: " + var);
}
return result;
}
public static void main( String args[] ) {
int number = 1745;
System.out.println("Number: " + number);
System.out.println( "Sum of digits in 1024 is: "+ sumOfDig(number) );
}
}

Understanding the code

  • Line 3: We start by declaring an int result variable to store the sum.

    ...