Skip to main content

How to check if a number is a power of two in Kotlin

How to check if a number is a power of two in Kotlin.

Here's a step-by-step tutorial on how to check if a number is a power of two in Kotlin:

Step 1: Get the input number from the user or define it in your code. Let's call it num.

Step 2: Check if the number is equal to 0. If it is, then it cannot be a power of two. In this case, you can return false or handle the error condition as per your requirement.

Step 3: Use the bitwise AND operator (&) to check if the number is a power of two. This can be done by comparing the number with its bitwise complement (num and (num - 1)). If the result is 0, then the number is a power of two; otherwise, it is not.

Step 4: Create a function, let's call it isPowerOfTwo, to encapsulate the logic. This function takes an integer parameter num and returns a boolean value indicating whether the number is a power of two.

Step 5: Implement the isPowerOfTwo function in Kotlin:

fun isPowerOfTwo(num: Int): Boolean {
if (num == 0) {
return false
}
return num and (num - 1) == 0
}

Step 6: Test the function with different inputs to verify its correctness. For example:

fun main() {
val numbers = listOf(1, 2, 3, 4, 8, 16, 32, 64, 128, 256)

for (num in numbers) {
val isPowerOfTwo = isPowerOfTwo(num)
println("$num is a power of two: $isPowerOfTwo")
}
}

Output:

1 is a power of two: true
2 is a power of two: true
3 is a power of two: false
4 is a power of two: true
8 is a power of two: true
16 is a power of two: true
32 is a power of two: true
64 is a power of two: true
128 is a power of two: true
256 is a power of two: true

That's it! You have successfully implemented a function to check if a number is a power of two in Kotlin.