LeetCode 342. Power of Four, My Solution

Valentin Placido
2 min readOct 4, 2020

During this past week I have been spending more and more time on both LeetCode and HackerRank trying to solve new problems. This article will focus on solving problem 342 from LeetCode titled Power of Four.

The Problem

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Given the task above at first it may seem as a simple problem to solve but as you begin to think about how to start the problem you realize this problem is not as easy as it seems. So given I have to keep track and change the number that is passed through the function my first instinct is to implement recursion and the base cases I have set up are to check if the number is not a power of 4 are if the number is 0, if the number is 1, and if the number is not divisible able by 4. Below is my implementation in JavaScript.

if (num === 0) {
return false;
} else if (num === 1) {
return true;
} else if (!Number.isInteger(num/4)) {
return false;
} else {
return isPowerOfFour(num/4)
}

Solution Information

Runtime: 100 ms, faster than 56.47% of JavaScript online submissions for Power of Four.

Memory Usage: 40 MB, less than 5.04% of JavaScript online submissions for Power of Four

--

--