public class FindNthSetBit32 {
/**
findNthSetBit32:
----------------
Given:
- x : a 32-bit integer (treated as unsigned)
- n : which set bit to find (1-based index)
Returns:
A 32-bit mask with ONLY the Nth set bit of x turned on.
If n is larger than the number of set bits, returns 0.
Algorithm:
- Use Integer.numberOfTrailingZeros(x) to locate the lowest set bit.
- Remove that bit using x &= (x - 1).
- When we reach the Nth one, return 1 << index.
Notes:
- Java does not have unsigned 32-bit primitives, but bitwise
operations behave identically for our purposes.
- numberOfTrailingZeros(x) is extremely efficient and maps to
a single CPU instruction on most architectures.
*/
public static int findNthSetBit32(int x, int n) {
while (x != 0) {
// Index (0–31) of the lowest set bit
int index = Integer.numberOfTrailingZeros(x);
// If this is the Nth set bit, return a mask with ONLY that bit set
if (--n == 0) {
return 1 << index;
}
// Remove the lowest set bit
x &= (x - 1);
}
// Fewer than n set bits
return 0;
}
// Convert a 32-bit integer to a binary string padded to 32 bits
public static String toBinary32(int x) {
String s = Integer.toBinaryString(x);
return "0".repeat(32 - s.length()) + s;
}
public static void main(String[] args) {
int value = 0b00001101001101101100100010100000;
int n = 4;
int result = findNthSetBit32(value, n);
System.out.println("Input value: " + toBinary32(value));
System.out.println("N = " + n);
System.out.println("Result mask: " + toBinary32(result));
}
}
/*
run:
Input value: 00001101001101101100100010100000
N = 4
Result mask: 00000000000000000100000000000000
*/