Bits Problems
Bit manipulation techniques, basic operations, and common interview problems.
Basic Operations
•
Check if a number is power of 2 → x != 0 && ((x & (x - 1)) == 0)
Easy
Theory
•
Calculate 2^n → 1 << n
Easy
Theory
•
XOR of two numbers → a ^ b
Easy
Theory
•
XOR of two numbers without XOR operator → (a | b) & (~a | ~b)
Medium
Theory
•
Multiply by 2 → x << 1
Easy
Theory
•
Divide by 2 → x >> 1
Easy
Theory
Left & Right Most Bits
•
LeftMostBitNo of x → x != 0, { y=1; while(x>1) { x=x>>1; y=y<<1; } return y; }
Medium
Theory
•
Turn off LeftMostBit → x & ~y
Medium
Theory
•
RightMostBitNo → x != 0, x & ~(x-1) OR (x & -x)
Medium
Theory
•
Turn off RightMostBit → x != 0, x & (x-1)
Medium
Theory
Missing Numbers & Binary Operations