Java Interviews: DSA - Bit Manipulation
Binary Left Shift (Multiplies):
a << b = a * (2^b)
Original : 0 0 0 0 1 0 1 : Int (5) Shift Left: 0 1 0 1 0 0 : Int (20)
if a = 5, b = 2, hence 5 << 2 and 5 * (2 ^ 2) Therefore 20.
Binary Right Shift (Divides):
a << b = a / (2^b)
Original : 0 1 0 1 0 0 : Int (20) Shift Left: 0 0 0 0 1 0 1 : Int (5)
if a = 20, b = 2, hence 20 << 2 and 20 / (2 ^ 2) Therefore 5.
Sample Interview Questions:
1) Odd Even
if(x&1){
System.out.println("Odd");
}
else{
System.out.println("Even");
}
2) Getting the iTH bit
Take a empty bit, and move the 1 to ith location, such that we can perform AND (&) to the n
number.
Step 1: Given: n=5, i=2 n in 0 0 0 1 0 1
Step 2:
Build a bit, such that it only has 1
in the ith Location using LeftShift.
mask=0 0 0 0 0 0 0 x<<i i.e. 0 0 0 1 0 0
Step 3: Perform AND with n and mask, res = n & mask (this will multiply)