Introduction-
Today, let’s learn about a famous and commonly asked Interview Problem, i.e,. Find the leftmost and rightmost set bit of a number.
Problem Statement: Find the position of the first set bit (i.e. 1) from
- right to left and
- Left to right
in binary representation of an Integer.
Example:
Input : Number = 17
Output:
Leftmost set bit : 5th position
Rightmost set bit: 1st position
(as the Binary representation of 17 is: 010001)
Let's get started and learn the approach to solve this problem.
Position of Rightmost Set Bit
Approach1
-
Take two’s complement of the given number as all bits are reverted except the first ‘1’ from right to left.
Note: 2’s complement is negation (~) of the given number + 1 (i.e. ~ N + 1)
(Example: Given No : 12 [1100] => Its 2’s complement would be 4 [0100])
- Do a Bitwise and(&) with original number => returns the required one only [0100]
- Take log2 of the number got in Step2 and you’ll get (position - 1).
- Add 1 to get the desired position (i.e. position of the rightmost set bit).
(=> 3 gets returned in this case)
So, (N & ~ ( N - 1 )) always returns the binary number containing the rightmost set bit as 1.
Implementation-
Let’s have a look at its implementation in Java -
You can also try this code with Online Java Compiler |
Output:
|
Time and Space Complexity-
Time Complexity: O(log2(N)) where “N” is the given number for calculating log2(N & ~ N) + 1.
Space Complexity: O(1) as no extra space has been used.
Approach2
Using Xor and & operator
Initialize m (mask bit) as 1 and check its XOR with the bits starting from the rightmost bit. Leftshift m by 1 till we find the first set bit. The first set bit gives the number = answer of a & operation with m.
Implementation-
Let’s have a look at its implementation in Java -
You can also try this code with Online Java Compiler |
Output:
|




