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

1 Answer

0 votes
import java.lang.Integer

/*
    findNthSetBit32:
    ----------------
    Given:
        - x : a 32-bit integer
        - 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 and (x - 1).
        - When we reach the Nth one, return 1 shl index.
*/
fun findNthSetBit32(x0: Int, n0: Int): Int {
    var x = x0
    var n = n0

    while (x != 0) {

        // Index (0–31) of the lowest set bit
        val index = Integer.numberOfTrailingZeros(x)

        n -= 1
        if (n == 0) {
            return 1 shl index
        }

        // Remove the lowest set bit
        x = x and (x - 1)
    }

    // Fewer than n set bits
    return 0
}

/*
    toBinary32:
    -----------
    Convert integer to a padded 32-bit binary string.
*/
fun toBinary32(x: Int): String {
    val s = Integer.toBinaryString(x)
    return s.padStart(32, '0')
}

fun main() {
    val value = 0b00001101001101101100100010100000
    val n = 4

    val result = findNthSetBit32(value, n)

    println("Input value:  ${toBinary32(value)}")
    println("N = $n")
    println("Result mask:  ${toBinary32(result)}")
}



/*
run:

Input value:  00001101001101101100100010100000
N = 4
Result mask:  00000000000000000100000000000000

*/

 



answered Jul 25 by avibootz
...