Bit Manipulation Bit basics
103. Check the i-th Bit
You are given an integer n and a bit position i. Return true if bit i of n is 1, and false
if it is 0.
n is stored as a 64-bit signed integer, so it has 64 bits. They are numbered from the right, starting
at 0: bit 0 is the 1s place, bit 1 is the 2s place, and bit i is the 2i place. For example,
5 is 101 in binary, so bits 0 and 2 of 5 are 1, and every other bit is 0.
A negative number is stored in two's complement: −x is the bits of x flipped, plus 1. So −1 is 64
ones, and every negative number has bit 63 set. In Python and JavaScript, n is an ordinary number, and
its bits are the same 64 bits.
Example 1
Input: n = 13, i = 2
trueExplanation: 13 = 8 + 4 + 1, so in binary it is 1101. Counting from 0 at the right, bit 2 is the 4s place, and
it is 1.
Example 2
Input: n = -6, i = 40
trueExplanation: −6 is stored as 61 ones followed by 010. Every bit from bit 3 to bit 63 is 1, so bit 40 is 1.
Example 3
Input: n = 6000000000, i = 31
falseExplanation: 6,000,000,000 = 232 + 1,705,032,704. The second part is less than 231, so bit 31 is 0. Bit 32 holds the 1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
-(253 − 1) ≤ n ≤ 253 − 10 ≤ i ≤ 63
Clarifying questions
What you would ask an interviewer before writing any code.