Check if a Number is Odd or Not
EasyThe lowest bit is the parity
Problem
Return whether an integer is odd using bit operations.
AND the number with 1 — if the lowest bit is set, it's odd.
The idea
In binary the last bit carries the value 1, so it is set exactly for odd numbers. `x & 1` therefore answers the question without a division, and unlike `x % 2` it behaves the same for negative numbers.
The trick
- `x & 1` is 1 for odd, 0 for even.
- `x % 2` returns -1 for negative odd values in C++ and Java; the mask does not.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — 7 Values: 7.
1return (n & 1) == 1Input
- array
- [7]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- n = 7
- Output:
- true
- Explanation:
- 7's last bit is 1, so it's odd.
Example 2
- Input:
- n = 10
- Output:
- false
- Explanation:
- 10 ends in bit 0 → even.
Example 3
- Input:
- n = 1
- Output:
- true
- Explanation:
- 1 is odd.
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.