Coding Exercise 17: Even Digit Sum

2021. 3. 13. 10:44Java programming

Write a method named getEvenDigitSum with one parameter of type int called number.

 

The method should return the sum of the even digits within the number.

 

If the number is negative, the method should return -1 to indicate an invalid value.

 

public class EvenDigitSum {
    public static int getEvenDigitSum(int number){
        if (number < 0)
            return -1;

            int sum = 0;

            while (number > 0){
                if (number % 2 == 0){
                    sum = (sum) + (number % 10);

            }
                number = number / 10;
        } return sum;
    }
}

이번 과제는 주어진 숫자들 중 짝수들만 찾아서 합을 구하는 문제이다.

 

'if (number % 2 == 0)'를 사용해 주어진 숫자를 2로 나눈 나머지가 0이면(짝수이면) 계속 루프를 진행시킨다.

 

'number % 10' 을 통해 주어진 숫자 number의 마지막 자릿수의 정수를 추려낸다.

 

while문 안에서 'number / 10' 은 마지막 자릿수를 한 자리씩 이동시켜 number 각 자릿수의 정수들을 체크한다.

 

To combine altogether,  we've got that solution above.

 

Nicely done to myself.