Sunday, December 13, 2020

Java program to get only the even digit sum of a given integer

 Yet another coding challenge I came across and here is the challenge ; 

you are given an Integer number

return - 1 if it is a negative number

if not, calculate the sum of all the even digits of the given number

    e.g:- 1658 is given then sum = 6 + 8 which is 14

below is my solution and I hope it helps

public class EvenDigitSum {
public static int getEvenDigitSum(int number){
int sumOfEvenDigits = 0;

if(number < 0){
sumOfEvenDigits = -1;
}else{
int lengthOfNumber = String.valueOf(number).length();

for(int i=0 ; i< lengthOfNumber ; i++){
int currentNumber = Character.getNumericValue(String.valueOf(number).charAt(i));
if(currentNumber % 2 == 0){
sumOfEvenDigits += currentNumber;
}else{
continue;
}
}
}
return sumOfEvenDigits;
}
}


No comments:

Post a Comment