A kind of one liner math javascript solution


  • 0
    /**
     * @param {number} num
     * @return {boolean}
     */
    var isPowerOfFour = function(num) {
    
           if(num <=0)
           return false;
           else if(num === 1)
           return true;
           
           return (num&(num-1)) === 0 && (num%10 === 4 || num%10 === 6);
    };
    

    As we all know , every power of 4 will also be a power of 2.

    We check for power of 2 using n&(n-1).

    List of powers of 2 which have powers of 4 -

    1 (power of 4)

    2

    4 (power of 4)

    8

    16 (power of 4)

    32

    64 (power of 4)

    128

    256 (power of 4)

    and so on.

    Every alternate power of 2 provides us power of 4. Reason is for power of 4 , we require another multiplication with 2 .

    So , if we closely observe , powers of 4 always end with 4 or 6 in one's place.

    Of course, if we want to generalize the task for any base - we need logarithms, but atleast we can optimize for some bases.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.