Check if a Number is Odd or Even
Solve this Problem
Given an integer
n, which may be negative, determine whether it's odd.
Dividing by 2 and checking the remainder works, but there's a more direct route: parity lives entirely in a number's lowest bit. ANDing n with 1 reads that bit straight from its binary representation — no division involved, and the trick holds for negative numbers just as cleanly as positive ones.
Test Case 1:
Input:n = 4
Output:false
Explanation:4 is even — its lowest bit is 0.
Test Case 2:
Input:n = 7
Output:true
Explanation:7 = 111 in binary — its lowest bit is 1, so it's odd.
Test Case 3:
Input:n = -3
Output:true
Explanation:Negative numbers work the same way — -3's lowest bit is still 1.
Constraints
- ◆
-2³¹ ≤ n ≤ 2³¹ − 1
🚀
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Modulo Operator
GoodThe remainder of n divided by 2 is zero for even numbers and nonzero for odd ones — check whether that remainder is nonzero.
Time
O(1)Space
O(1)Java
1class Solution {
2 public boolean isOdd(int n) {
3 int remainder = n % 2;
4 return remainder != 0;
5 }
6}Optimal — Bitwise AND with 1
OptimalIn binary, only the least significant bit distinguishes an odd number from an even one — AND n with 1 to read that bit directly, with no division involved. Two's complement keeps that same bit as the parity indicator for negative numbers too, so the trick needs no special case for sign.
Time
O(1)Space
O(1)Java
1class Solution {
2 public boolean isOdd(int n) {
3 int lastBit = n & 1;
4 return lastBit == 1;
5 }
6}