Learner Level

Implement the powerOfFourCheck method that checks whether a number is a power of four.

The input is an integer n.

Your task is to check whether n is a power of four. A number is a power of four if it can be written as 4^k for some non-negative integer k.

For example, 16 is a power of four because 4 × 4 = 16. 5 is not a power of four.

Example 1

Input
n (int) = 16
Returns (boolean) true

Example 2

Input
n (int) = 5
Returns (boolean) false

Example 3

Input
n (int) = 1
Returns (boolean) true

Keep dividing the number by 4 while it is exactly divisible by 4.

If the number finally becomes 1, then it was made only by multiplying 4 repeatedly. If it becomes any other value, then it is not a power of four.

Negative numbers and zero are never powers of four.

Pseudocode:

function powerOfFourCheck(n):
    if n <= 0:
        return false
    while n % 4 == 0:
        n = n / 4
    return n == 1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.