Power of 4

Posted on Sat 15 August 2020 in tech

This one line solution bests 100% of Java submissions on leetcode.

I have to out myself. When I was a junior programmer I would have been strongly morally opposed to a solution like this. First of all, that was three decades ago and back then many types of cpus did not have integrated floating point co-processors. In fact, many cpus did not have any floating point processing capability at all. In that case the workload of floating point calculations had to be done in software. These operations were expensive and could take hundreds of clocks for simple operations.

Much has changed since then. Today, the performance of floating point operations, especially uncomplicated ones, can be on par with integer math. As a result times have changed and we have to change with it.

The best solution to the 'isPowerOfFour' puzzle is straight up log math. A simple epsilon check for zero is added just to be on the safe side. This solution bests 100% of Java solutions as of August 2020.

    public boolean isPowerOfFour(int num) {
        final var epsilon = Math.log(num)/Math.log(4.0) % 1.0;

        return epsilon < 1e-8 && epsilon> -1e-8;