Skip to content

Commit 2c0b9f7

Browse files
committed
rightmost bit find position
1 parent 890223b commit 2c0b9f7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package binary.rightmostBit;
2+
3+
import utils.InputReader;
4+
5+
public class RightmostBitPositionFinder {
6+
public static void main(String[] args) {
7+
System.out.print("Input a number: ");
8+
int x = InputReader.readInt();
9+
//unset the rightmost bit of number & XOR the result with number
10+
System.out.print("Result: " + positionOfRightmostSetBit(x));
11+
}
12+
13+
static int positionOfRightmostSetBit(int n)
14+
{
15+
// if the number is odd, return 1
16+
if ((n & 1) != 0) {
17+
return 1;
18+
}
19+
20+
// unset rightmost bit and xor with the number itself
21+
n = n ^ (n & (n - 1));
22+
23+
// find the position of the only set bit in the result;
24+
// we can directly return `log2(n) + 1` from the function
25+
int pos = 0;
26+
while (n != 0)
27+
{
28+
n = n >> 1;
29+
pos++;
30+
}
31+
return pos;
32+
}
33+
}

0 commit comments

Comments
 (0)