Solution Review: Sum of Digits in an Integer
In this review, solution of the challenge 'Sum of Digits in an Integer' from the previous lesson is provided.
Solution
Java
class SumDigits {public static int sumOfDig(int var) {int result = 0; //variable for resultant sumint lastDigit = 0;while (var > 0) {//seclude & keep adding the last digit into resultlastDigit = var % 10;result = result + lastDigit;System.out.println("Last Digit: " + lastDigit);System.out.println("Sum: " + result);var /= 10; //update the new value of varSystem.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.
...