The Bitwise Judge
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- i360
Problem
Given an integer n (possibly negative), return True if n is even, False if odd. Solve using bitwise operations only - no %, no /, no //.
No division, no modulo - just a single bit tells you everything.
Example 1
Input:
n = 4
Output:
true
Example 2
Input:
n = 7
Output:
false
Worked solution and explanation
Why this problem exists in real interviews
Checking even/odd with bitwise AND tests the most basic bit manipulation concept: the least significant bit determines parity.
Break down the requirements
Step 1: Check the least significant bit
If n & 1 is 0, the number is even. If 1, it is odd.
The solution
def is_even(n):
result = (n & 1) == 0
return resultCommon follow-up questions
- How would you check if a number is a power of 2? (Tests `n > 0 and (n & (n - 1)) == 0`, which checks that only one bit is set.)
- What if n is negative? (Tests that bitwise AND on negative numbers in Python works with two's complement, and the LSB check still determines parity.)
- Can you check divisibility by 4 using bitwise operations? (Tests `(n & 3) == 0`, checking the two least significant bits.)