Count Number of bit from 1 to n in Kotlin

To calculate the total number of bits from 1 to n, we can iterate over all the numbers from 1 to n and count the number of bits in each number. We can use the Integer.bitCount() method in Java or the countOneBits() method in Kotlin to count the number of bits in each number. Then, we can add up the number of bits in each number to get the total number of bits from 1 to n.

Here’s an example implementation in Kotlin:

Kotlin
fun countBits(n: Int): Int {
    var totalBits = 0
    for (i in 1..n) {
        totalBits += Integer.bitCount(i)
    }
    return totalBits
}
fun main() {
    val n = 10
    val totalBits = countBits(n)
    println("Total number of bits from 1 to $n: $totalBits")
}

Here, we first initialize a variable totalBits to 0. We then iterate over all the numbers from 1 to n using a for loop and count the number of bits in each number using the Integer.bitCount() method. We add the number of bits in each number to totalBits and return it as the result.

we set the value of n to 10, and then call the countBits() function with n as the argument. We store the result in a variable totalBits, and then print the result using println(). The output of this program would be: Total number of bits from 1 to 10: 17

Leave a Comment