AlgoViz

Check if the i-th bit is Set or Not

Easy

Shift the bit down, or the mask up

Problem

Given a number and an index i, return whether the i-th bit (0-indexed) is 1.

In simple words

Shift a single 1 to position i and AND it with the number — nonzero means the bit is on.

The idea

Either shift the number right by i and test the lowest bit, or shift a 1 left by i and AND it against the number. Both are single operations; the first is usually clearer because the result is already 0 or 1.

The trick

  • `(x >> i) & 1` gives exactly 0 or 1.
  • `x & (1 << i)` is non-zero when set, but not necessarily 1.
  • For i >= 31 use a 64-bit shift, or the behaviour is undefined.

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.

13
2
0
1

Step 1 of 2. Here's the example — n=13, i=2 Values: 13, 2.

1/2
Optimal
timeO(1)spaceO(1)
1return (n >> i) & 1 == 1

Input

array
[13, 2]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
n = 5, i = 0
Output:
true
Explanation:
5 is 101; bit 0 is 1.

Example 2

Input:
n = 5, i = 1
Output:
false
Explanation:
5 is 101; bit 1 is 0.

Example 3

Input:
n = 8, i = 3
Output:
true
Explanation:
8 is 1000; bit 3 is 1.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.