Power of Two using Python

The problem of Power of Two is a popular coding interview question. Here we need to check whether the input value is the power of two or not. So, if you want to know how to solve this problem using Python, this article is for you. In this article, I will take you through how to solve the problem of the power of two using Python.

Power of Two using Python

In the problem of the power of two, you will be given an integer. You need to return True if the integer is a power of two; otherwise, return False. Below are some examples of the input and output of this problem:

Example: 1
Input: 16
Output: true

Example: 2
Input: 3
Output: false

I hope you have understood what the problem of the power of two means. Now, below is how you can solve this problem using the Python programming language:

def isPowerOfTwo(n):
    while (n != 1):
        if (n % 2 != 0):
            return False
        n = n // 2
    else:
        return True
print(isPowerOfTwo(16))
Output: True

So this is how to check if an integer is a power of two or not using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

In the problem of the power of two, you will be given an integer. You need to return True if the integer is a power of two; otherwise, return False. I hope you liked this article on solving the problem of the power of two. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1334

Leave a Reply