Skip to content

Commit 48165e0

Browse files
committed
find the only set bit of a number
1 parent 2c0b9f7 commit 48165e0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)