Cracking the LeetCode - 342

Power of Four

Introduction

Got a quick and easy challenge this time around which has been rare. I have been exclusively coding in C# for LeetCode recently as I am using Python for my side project so there will only be one solution.

Problem

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4<sup>x</sup>.

Examples

Example 1:

Input: n = 16
Output: true

Example 2:

Input: n = 5
Output: false

Example 3:

Input: n = 1
Output: true

Constraints

  • -2<sup>31</sup> <= n <= 2<sup>31</sup> - 1

Process

I don't mean to toot my own horn but I was also pretty good at Mathematics in school. My immediate thought was to use a log function to determine the result and all that was needed next was to figure out if the result is an integer value.

For those that aren't aware, log functions are inverses of exponential functions. So using the problem statement as an example: n == 4<sup>x</sup> is the same as log~4~ (n) = x . Given n, x can be solved and then using a basic modulo operation to determine if x is an integer.

Solution

C

Here is the final C# solution:

public class Solution {
    public bool IsPowerOfFour(int n) {
        double x = Math.Log(n, 4);
        return (x % 1) == 0;
    }
}

Conclusion

Was a nice change of pace to be able to do a challenge that didn't require hours of problem-solving for me. Given how easy it was, it would probably have been a good idea to play around with performance and memory but I'm finding the specs given for Runtime a bit random. It must be based on a random subset of the available tests because the same code can give drastically different numbers when re-submitted. This has turned me off trying to make improvements as it's very hard to tell if the changes made are making a difference or not.