Count the number of set bit in a integer in Kotlin

To count the number of set bits (i.e., bits set to 1) in an integer, we can use bit manipulation. One approach is to use a loop to check each bit of the integer, starting with the least significant bit. We can do this by right-shifting the integer by 1 bit at a time and checking the rightmost bit using the bitwise AND operator. If the rightmost bit is 1, we increment a counter. We repeat this process until the integer becomes 0.

Here’s an example implementation in Kotlin:

Kotlin
fun countSetBits(n: Int): Int {
    var count = 0
    var num = n
    while (num != 0) {
        count += num and 1
        num = num shr 1
    }
    return count
}
fun main() {
    val n = 23
    val result = countSetBits(n)
    println("Number of set bits in $n: $result")
}

Here, we first initialize a variable count to 0 to count the number of set bits. We also initialize a variable num to the value of n. We then enter a loop that continues as long as num is not 0. Inside the loop, we check the rightmost bit of num using the bitwise AND operator (&) with 1. If the result is 1, we increment the count variable. We then right-shift num by 1 bit using the shr operator and repeat the process. Once num becomes 0, we exit the loop and return the count variable.

We can then call the countSetBits() function with a number and print the result using println()

This will output: Number of set bits in 23: 4

Leave a Comment