/*
countTrailingZeros:
-------------------
Returns the number of trailing zeros in a 32‑bit integer.
TypeScript types:
- x: number (treated as 32‑bit via bitwise ops)
- returns number (index 0–31)
Algorithm:
- Isolate lowest set bit: x & -x
- Its index is log2(lowest_bit)
*/
function countTrailingZeros(x: number): number {
const lowest: number = x & -x; // isolate lowest set bit
return Math.log2(lowest); // index of that bit (0–31)
}
/*
findNthSetBit32:
----------------
Given:
- x : number (32-bit integer)
- n : number (1-based index)
Returns:
number — a mask with ONLY the Nth set bit turned on,
or 0 if n exceeds the number of set bits.
Algorithm:
- Use countTrailingZeros(x) to locate the lowest set bit.
- Remove that bit using x &= (x - 1).
- When we reach the Nth one, return 1 << index.
*/
function findNthSetBit32(x: number, n: number): number {
while (x !== 0) {
const index: number = countTrailingZeros(x);
n -= 1;
if (n === 0) {
return 1 << index;
}
x &= (x - 1);
}
return 0;
}
/*
toBinary32:
-----------
Convert integer to a padded 32-bit binary string.
Types:
- x: number
- returns string
*/
function toBinary32(x: number): string {
const unsigned: number = x >>> 0; // force unsigned 32-bit
const s: string = unsigned.toString(2); // binary string
return s.padStart(32, "0");
}
// --------------------
// Main
// --------------------
const value: number = 0b00001101001101101100100010100000;
const n: number = 4;
const result: number = findNthSetBit32(value, n);
console.log("Input value: ", toBinary32(value));
console.log("N =", n);
console.log("Result mask: ", toBinary32(result));
/*
run:
Input value: 00001101001101101100100010100000
N = 4
Result mask: 00000000000000000100000000000000
*/