Given an integer, write a program to clear the right most set bit in it’s binary representation.
For example, consider a number 54. It is represented in binary as
1 1 0 1 1 0.
The right most set bit is marked in bold. We need to convert this to
1 1 0 1 0 0
Let us look at the approach step by step.
If you negate the number to -54, it is represented in computer’s memory in 2’s compliment.
0 0 1 0 1 0
Let us perform a bit-wise AND operation between these two.
1 1 0 1 1 0
0 0 1 0 1 0
————&
0 0 0 0 1 0
Subtract this from the original number to get the result. So x – ( x & -x) gives the required answer.
Here is the simple program to test the above.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Ravi on 18-Nov-14. | |
*/ | |
public class ClearRightmostSetBit | |
{ | |
public static void main(String []args) | |
{ | |
Test(); | |
} | |
private static void Test() | |
{ | |
int x = 54; | |
System.out.println("Input: " + Integer.toBinaryString(x)); | |
x = clearRightmostSetBit(x); | |
System.out.println("Output: " + Integer.toBinaryString(x)); | |
x = 1; | |
System.out.println("Input: " + Integer.toBinaryString(x)); | |
x = clearRightmostSetBit(x); | |
System.out.println("Output: " + Integer.toBinaryString(x)); | |
x = 8; | |
System.out.println("Input: " + Integer.toBinaryString(x)); | |
x = clearRightmostSetBit(x); | |
System.out.println("Output: " + Integer.toBinaryString(x)); | |
x = 15; | |
System.out.println("Input: " + Integer.toBinaryString(x)); | |
x = clearRightmostSetBit(x); | |
System.out.println("Output: " + Integer.toBinaryString(x)); | |
} | |
public static int clearRightmostSetBit(int num) | |
{ | |
if( num != 0 ) | |
return num - (num & -num); | |
return num; | |
} | |
} |