-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f0e8ba7
commit bbdbae4
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
Exercise 17 - Even Digit Sum (Question and Answer)/EvenDigitSum.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
|
||
|
||
public class EvenDigitSum { | ||
public static void main(String[] args){ | ||
System.out.println(getEvenDigitSum(1234)); | ||
} | ||
public static int getEvenDigitSum(int number){ | ||
//initialisation | ||
int sum = 0; | ||
int box = 0; | ||
// invalid options | ||
if (number < 0) { | ||
return -1; | ||
} | ||
while (number >= 0) { | ||
if (number % 2 == 0) { | ||
sum = number % 10; | ||
box += sum; | ||
} | ||
number /= 10; | ||
|
||
} | ||
return box; | ||
|
||
} | ||
} | ||
|
||
// Even Digit Sum | ||
// Press Write a method named getEven DigitSum 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. | ||
// EXAMPLE INPUT/OUTPUT: | ||
// • | ||
// getEvenDigitSum(123456789); – should return 20 since 2 + 4 + 6 + 8 = 20 | ||
// getEvenDigitSum(252); – should return 4 since 2 + 2 = 4 | ||
// getEvenDigitSum(-22); → should return -1 since the number is negative | ||
// |