How to round a number to the next power of 2 in Kotlin

1 Answer

0 votes
import kotlin.math.ceil
import kotlin.math.log2
import kotlin.math.pow

fun roundToNextPowerOf2(n: Int): Int {
    return if (n <= 0) 1 else 2.0.pow(ceil(log2(n.toDouble()))).toInt()
}

fun main() {
    val num = 21
    
    println("Next power of 2: ${roundToNextPowerOf2(num)}")
}




/*
run:

Next power of 2: 32

*/

 



answered Oct 29, 2025 by avibootz
...