Sum of Even and Odd Digits
Problem
Read an integer. Print the sum of its even digits on the first line and the sum of its odd digits on the second line. Ignore the minus sign. Zero is an even digit.
Constraints
- -10^12 <= n <= 10^12
Examples
Input
12345
Output
Even digits sum: 6 Odd digits sum: 9
Solutions
We peel digits off the number one by one with % 10 and / 10, and we add each digit to one of two sums depending on its parity. Math.abs removes the minus sign first.
/*
* Problem : Sum the even digits and the odd digits separately.
* Input : One integer.
* Output : Two lines with the two sums.
* Approach: Take digits one by one and test each digit.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = Math.abs(new Scanner(System.in).nextLong());
// Step 1: Start both sums with 0.
int evenSum = 0;
int oddSum = 0;
// Step 2: Repeat until no digits are left.
while (number > 0) {
// Step 3: Take the last digit. Example: 12345 % 10 = 5.
int digit = (int) (number % 10);
// Step 4: Add the digit to the even sum or to the odd sum.
if (digit % 2 == 0) {
evenSum = evenSum + digit;
} else {
oddSum = oddSum + digit;
}
// Step 5: Remove the last digit. Example: 12345 / 10 = 1234.
number = number / 10;
}
// Step 6: Print both sums. For the number 0 both sums stay 0.
System.out.println("Even digits sum: " + evenSum);
System.out.println("Odd digits sum: " + oddSum);
}
}
Hints (2)
- Which operator gives the last digit of a number?
- Which operation removes the last digit?