Find the Sum of Even Digits of a Number

Question : Find sum of digits of number that are even.
Suppose we have a number 456789 and we need to find the sum of all the digits in the number that are even or divisible by 2.
e.g In number  456789 sum of even digits is 4 + 6 + 8 = 18.
import java.util.Scanner;

class FindSum{

 public static void main(String args[]){

 System.out.println("Enter the number");
 Scanner sc = new Scanner(System.in);
 FindSum object = new FindSum();
 int number = sc.nextInt();
 int sum = object.findSumOfDigits(number);
 System.out.println("Sum of digits of "+number+" = "+ sum);
 }

 public int findSumOfDigits(int num){

  int sum = 0;
  while(num != 0){
    if((num % 10) %2 == 0)
    sum += num % 10;
    num = num / 10;  
  }
  return sum;
 }

}
Enter the number
456789
Sum of digits of 456789 = 18

In the above program we take the number as input from the user by using the Scanner class and then pass this number to the method findSumOfDigits() that calculates the sum of digits of the number. The while loop runs till the number is not zero.
In the while loop we add the last digit of the number to the sum and divide the number by 10 all we need to do extra is to check if the digit is divisible by 2, if yes then we add it to the sum or else we do not.. What happens is
456789 % 10(gives 9), if condition fails so we do not add it to the sum and num = 456789 / 10 = 45678 (since num is integer)
45678 % 10(gives 8), condition satisfies so we add it to sum, sum = 0 + 8 = 8 and num = 45678 / 10 = 4567 and so on.

No comments:

Powered by Blogger.