Question 9
Back to Exercise
Read a list of integers (including negatives) and print the count and sum of even and odd numbers, testing parity with & 1 instead of %.
Solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int evenCount = 0, oddCount = 0;
long evenSum = 0, oddSum = 0;
while (in.hasNextInt()) {
int n = in.nextInt();
if ((n & 1) == 0) { evenCount++; evenSum += n; } // works for negatives too
else { oddCount++; oddSum += n; }
}
System.out.println("even: " + evenCount + " numbers, sum " + evenSum);
System.out.println("odd: " + oddCount + " numbers, sum " + oddSum);
}
}
even: 4 numbers, sum 10 odd: 4 numbers, sum 70
n % 2 == 1 fails for negative odd numbers (-3 % 2 is -1), but n & 1 is 1 for every odd number in two's complement.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!