LearnFrenzy
Sign in Take a free test

Operators and Expressions · Java Operators Programs · Question 9

Sum of even and odd numbers using bitwise checks in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
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
Main.java
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);
    }
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links