Simplest C++ solution maybe?


  • 24
    D
    class Solution {
    public:           
        bool isPowerOfFour(int num) {
            return !(num & (num - 1)) && (num & 0x55555555);
        }
    };

  • 0
    N

    Impressive! Could you please explain how this works? Thank you :)


  • 1
    R

    (num & (num - 1)) ensures that binary form of num is start with 1 and only 1, like 0x100...000, (num & 0x55555555) ensures that the 1 bit is in position of power four, which can exclude 0x10, 0x1000, 0x100000, reserve 0x1, 0x100 and so on.


  • 0
    A

    My idea is the same as yours. Your code is more efficient when judging whether the given num is the power of 2 but I don't think this is a general algorithm for identifying if a number is the power of another given number..


  • 0
    T

    I agree, but the problem was to find power of 4. Notice that when you're writing a general isPowerOf(num, exp) you can use these specialized solutions to speed up calculations in case it's needed.


Log in to reply
 

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