Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to find the Nth set bit in a 32‑bit integer with TypeScript

1 Answer

0 votes
/*
    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

*/

 



answered Jul 25 by avibootz
...