import java.lang.Integer
object FindNthSetBit32 {
// Count trailing zeros using Java's built-in method
def countTrailingZeros(x: Int): Int =
Integer.numberOfTrailingZeros(x)
// Find the Nth set bit in a 32-bit integer
def findNthSetBit32(x0: Int, n0: Int): Int = {
var x = x0
var n = n0
while (x != 0) {
val index = countTrailingZeros(x)
n -= 1
if (n == 0)
return 1 << index
x &= (x - 1)
}
0
}
// Convert to padded 32-bit binary string
def toBinary32(x: Int): String = {
val s = Integer.toBinaryString(x)
"0" * (32 - s.length) + s
}
def main(args: Array[String]): Unit = {
val value: Int = 0b00001101001101101100100010100000
val n: Int = 4
val result: Int = 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
*/