Explain ((n & (n-1)) == 0)

Problem : Explain what the following code does: ((n & (n-1)) == 0). Solution When we have A & B == 0, it means that A and B have no common 1s, i.e. any two bits at the same positions of A and B are either different from each other, or two 0s. It works because a binary power of two is of the form 1000...000 and subtracting one will give you 111. [Read More]

Count bits set in an integer

Question: Write a function that determines the number of bits set to 1 in the binary representation of an integer. Method 1 - Simple method (Right shift integer until it becomes 0) Going by the brute force approach, it would be easy to come up with the following solution. If the least significant bit of a number is 1, it will return a result of 1 when we AND it with 1. [Read More]

Code to check if an integer is a power of 2 or not in a single line

Problem Check if integer is power of 2 or not FOLLOW UP - Preferable solution to get it in 1 line. Solution Method1 All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. We have discussed how to count number of bits set here. Method 2 Note that the bit pattern of a power of two is of the form 10…0 and that of a number just one less is 011…1. [Read More]