Odd or Even
Odd or Even is a easy bit manipulation problem solved with the basics pattern.
The best approach, lowest bit, runs in O(1) time and O(1) space.
Below are 2 approaches in Java, from modulo up.
Problem
Decide whether n is odd or even using a bit operation.
Examples
Example 1
- Input
n = 15- Output
odd
Example 2
- Input
n = 44- Output
even
Constraints
0 <= n <= 10^4(the bit trick also works for negative numbers in two's complement).
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Modulo | O(1) | O(1) |
| Lowest bit | O(1) | O(1) |
1Modulo
O(1)O(1)Check the remainder when dividing by 2. Compare with 0 rather than 1 so negative numbers work.
- return n % 2 == 0 ? even : odd.
class Solution {
static String oddEven(int n) {
return n % 2 == 0 ? "even" : "odd";
}
}2Lowest bit
O(1)O(1)n & 1 isolates the lowest bit: 1 means odd, 0 means even. It works for negative numbers too.
- return (n & 1) == 0 ? even : odd.
class Solution {
static String oddEven(int n) {
return (n & 1) == 0 ? "even" : "odd";
}
}Edge cases to test
- n = 0 (even)
- Negative n: n % 2 gives -1 in Java, so n % 2 == 1 is wrong for negatives
Hints
Hint 1
The lowest bit of a number is 1 exactly when it is odd.
FAQ
What is the best time complexity for Odd or Even?
Lowest bit runs in O(1) time and O(1) extra space.
Which pattern does Odd or Even use?
It is a bit manipulation problem that uses the basics pattern. Other problems with the same pattern: Decimal to binary, Convert Binary Number in a Linked List to Integer, K-th Bit is Set or Not.
Is there a brute force solution for Odd or Even?
Yes. Modulo takes O(1) time and O(1) space. Check the remainder when dividing by 2.
Which edge cases should I test for Odd or Even?
n = 0 (even); Negative n: n % 2 gives -1 in Java, so n % 2 == 1 is wrong for negatives.