File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
Expand file tree Collapse file tree 1 file changed +26
-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 OnlySetBitFinder {
6+ public static void main (String [] args ) {
7+ System .out .print ("Input a number: " );
8+ int x = InputReader .readInt ();
9+ System .out .print ("Position of only set bit: " + positionOfSet (x ));
10+ }
11+
12+ public static int positionOfSet (int n ) {
13+ // unset the rightmost bit and check if the number is non-zero
14+ if ((n & (n - 1 )) != 0 )
15+ {
16+ System .out .println ("Wrong input" );
17+ return 1 ;
18+ }
19+ // If 0, we can find the position of the only set bit by directly using log2(n) + 1.
20+ return log (n , 2 ) + 1 ;
21+ }
22+
23+ public static int log (int x , int base ) {
24+ return (int ) (Math .log (x ) / Math .log (base ));
25+ }
26+ }
You can’t perform that action at this time.
0 commit comments