WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Coding Interview Essentials Β· Bit Manipulation Problems Β· question 81 of 120

How would you check if a number is a power of 2 using bit manipulation?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

If a number is a power of 2, it has one set bit in its binary representation and all other bits are unset.

Here is the binary representation of powers of 2:


$$\begin{aligned} 2^0 & = 1 & = 0001\_b \\ 2^1 & = 2 & = 0010\_b \\ 2^2 & = 4 & = 0100\_b \\ 2^3 & = 8 & = 1000\_b \\\end{aligned}$$

As you can see, these binary representations only have one bit set (one ’1’) and the rest are zeroes. This is a defining characteristic of powers of 2.

We can express this characteristic using bit manipulation. If β€˜nβ€˜ is a power of 2, then β€˜nβ€˜ AND β€˜n-1β€˜ will be β€˜0β€˜.

Let’s examine this. If β€˜nβ€˜ is a power of 2, we have a binary representation like β€˜1000...0β€˜. Now, β€˜n-1β€˜ will be β€˜0111...1β€˜. When we do a bitwise AND operation (β€˜&β€˜), every bit of the result will be β€˜0β€˜ because β€˜1β€˜ AND β€˜0β€˜ yields β€˜0β€˜ and β€˜0β€˜ AND β€˜1β€˜ also yields β€˜0β€˜.

More formally, let’s represent the number as 2k. Then the binary representation of 2k in a sufficiently large number of bits is:


2k = 1000...0

And 2kβ€…βˆ’β€…1 is:


2kβ€…βˆ’β€…1 = 0111...1

So, the bitwise AND of these two numbers:


2k&(2kβ€…βˆ’β€…1) = 0000...0 = 0

You can implement this as a function in any language that supports bitwise operations. For example, in Java:

boolean isPowerOfTwo(int n) {
  if(n <= 0) return false;
  return (n & (n - 1)) == 0;
}

This function first checks if the number is positive (since the method doesn’t work for negatives or zero), then it returns whether β€˜n & (n - 1) == 0β€˜. If β€˜nβ€˜ is power of 2, this will be β€˜trueβ€˜, otherwise β€˜falseβ€˜.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview β€” then scores it.
πŸ“ž Practice Coding Interview Essentials β€” free 15 min
πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

All 120 Coding Interview Essentials questions Β· All topics