object PowerOfTwo {
/**
* Rounds an integer down to the previous power of 2.
*
* return the previous power of 2 less than or equal to n
*/
def roundToPreviousPowerOf2(n: Int): Int = {
if (n <= 0) 0
else 1 << (31 - Integer.numberOfLeadingZeros(n))
}
def main(args: Array[String]): Unit = {
val num = 21
println(s"Previous power of 2: ${roundToPreviousPowerOf2(num)}")
}
}
/*
run:
Previous power of 2: 16
*/