Power of Three using Python

The problem of the power of three is a popular coding interview question. Here we need to check whether the input value is the power of three 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 three using Python.

Power of Three using Python

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

Input: 27
Output: true

Input: 5
Output: false

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

def isPowerOfThree(n):
    while (n != 1):
        if (n % 3 != 0):
            return False
        n = n // 3
    else:
        return True
print(isPowerOfThree(27))
Output: True

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

Summary

The problem of the power of three is a popular coding interview question. In this problem, you will be given an integer. You need to return True if the integer is a power of three; otherwise, return False. I hope you liked this article on how to solve the problem of the power of three using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1498

Leave a Reply