Check whether a Given Number is Even or Odd
Problem
Given an integer N (which may be negative), return "Even" if it is divisible by 2 and "Odd" otherwise. Solve it without using the modulo or division operator as a follow-up.
Input / Output
- Input: integer
N. - Output: the string
"Even"or"Odd".
Examples
| N | Output |
|---|---|
| 4 | Even |
| 7 | Odd |
| 0 | Even |
| -3 | Odd |
| -10 | Even |
Constraints
-10^18 <= N <= 10^18
Approach
Modulo. N % 2 == 0 → even. Beware that in C, C++, Java and JavaScript the result of % for a negative operand can be -1, so test N % 2 == 0 rather than N % 2 == 1.
Bitwise (preferred). In two's-complement representation the least-significant bit is 1 for every odd number and 0 for every even number, positive or negative. So:
if (N & 1) == 0: Even else Odd
This is branch-free, works for negatives without special cases, and is what the follow-up is looking for.
Other tricks worth mentioning.
(N >> 1) << 1 == N— shifting right then left clears the lowest bit; equality means it was already 0.N ^ 1 == N + 1holds only for evenN.
Complexity
- Time: O(1)
- Space: O(1)
Interview angle
The question is a warm-up used to move into bit manipulation: expect follow-ups such as checking whether a number is a power of two (N & (N-1) == 0), counting set bits, or finding the single odd-occurring element with XOR.
Reference solution (Python)
def parity(n: int) -> str:
return "Even" if (n & 1) == 0 else "Odd"
Test cases
| Input | Expected |
|---|---|
4 | Even |
7 | Odd |
0 | Even |
-3 | Odd |