In Java, how to get positions of ones in reversed binary form of an integer?
You can just test the bits without turning the integer into a string:
List<Integer> onePositions(int input) {
List<Integer> onePositions = new ArrayList<>();
for (int bit = 0; bit < 32; bit++) {
if (input & (1 << bit) != 0) {
onePositions.add(bit + 1); // One-based, for better or worse.
}
}
return onePositions;
}
Bits are usually counted from right to left, the rightmost bit being bit 0. The operation 1 << bit
gives you an int
whose bit numbered bit
is set to 1 (and the rest to 0). Then use &
(binary and) to check if this bit is set in the input
, and if so, record the position in the output array.
Just check the bits in turn:
List<Integer> bits(int num) {
List<Integer> setBits = new ArrayList<>();
for (int i = 1; num != 0; ++i, num >>>= 1) {
if ((num & 1) != 0) setBits.add(i);
}
return setBits;
}
Online Demo
6 [2, 3]
7 [1, 2, 3]
8 [4]