Check if the i-th Bit is Set or Not

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given a number n and a bit position i (0-indexed from the least significant bit), determine whether the bit at position i is set (1) or clear (0). Every bit position in n can be isolated by lining it up with position 0 through a shift, or by building a mask that targets it directly — either way, the answer falls out of a single AND once the right bit lines up.

Test Case 1:

Input:n = 10, i = 1
Output:true
Explanation:10 = 1010 in binary — bit 1 (value 2) is set.

Test Case 2:

Input:n = 10, i = 0
Output:false
Explanation:Bit 0 (value 1) is clear in 1010.

Test Case 3:

Input:n = 1, i = 0
Output:true
Explanation:1 = 0001 — bit 0 is the only set bit.

Constraints

  • 0 ≤ n ≤ 2³¹ − 1
  • 0 ≤ i ≤ 31
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

Approach & Solutions

Right Shift and Mask

Good

Shift n right by i positions so the bit in question lands at position 0, then mask with 1 to read just that position.

TimeO(1)
SpaceO(1)
1class Solution { 2 public boolean isBitSet(int n, int i) { 3 int shifted = n >> i; 4 int bit = shifted & 1; 5 return bit == 1; 6 } 7}

Optimal — Mask the Target Bit Directly

Optimal

Instead of shifting n, build a mask with only bit i set (1 << i) and AND it against n directly — n itself never moves. The result is nonzero exactly when bit i was set, regardless of what value that bit contributes at its original position.

TimeO(1)
SpaceO(1)
1class Solution { 2 public boolean isBitSet(int n, int i) { 3 int mask = 1 << i; 4 int result = n & mask; 5 return result != 0; 6 } 7}

Related Problems