Check if a number is power of 2 using bit manipulation

To check whether a number is a power of 2 using bit manipulation, we can use the fact that a power of 2 has only one bit set in its binary representation. For example, 2 in binary is 10, 4 is 100, 8 is 1000, and so on. Therefore, if we subtract 1 from a power of 2, we get a number with all the bits set to the right of the bit that was set in the original power of 2. For example, if we subtract 1 from 8 (which is 1000 in binary), we get 7 (which is 0111 in binary). Therefore, if we take the bitwise AND of a power of 2 and its predecessor (i.e., the number obtained by subtracting 1), we get 0. For example, if we take the bitwise AND of 8 and 7, we get 0.

Here’s an example implementation in Kotlin:

Kotlin
fun isPowerOfTwo(n: Int): Boolean {
    return n > 0 && (n and (n - 1)) == 0
}
fun main() {
    val n = 16
    val result = isPowerOfTwo(n)
    println("$n is a power of 2: $result")
}

Here, we first check if n is greater than 0, because 0 is not a power of 2. We then take the bitwise AND of n and its predecessor n-1 using the and operator (&), and check if the result is equal to 0. If the result is 0, it means that n has only one bit set in its binary representation and is therefore a power of 2. If the result is not 0, it means that n has more than one bit set in its binary representation and is therefore not a power of 2.

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

This will output: 16 is a power of 2: trueCheck if a number is power of 2 using bit manipulation

Leave a Comment