File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments