Three if statements and 4ms cpp code


  • 2
    L
    class Solution {
    public:
        bool isPowerOfFour(int num) {
            int mask = 0x55555555;  // if you do 4^0 + 4^1 + 4^2 + 4^3 +..... in calc.exe in hex form
                                    // you will find this magical principle.
                                    // every time when add, the result is in form like "010101010101"
                                    // So, 0x55555555 can be the mask to see 
                                    // whether the num is partly matching power of 4
            if (num == 0)           // Special case.
                return false;
            if (num & (num - 1))    // Every num which is power of 4 just has one 1bit in its binary form
                return false;       // num & (num - 1) can judge if it is only one 1bit in its Binary
            if (num & (~mask))      // nums which can fit "only one 1 bit in its Binary" and "the 1 Bit
                return false;       // is at correct position" are the power of 4.
            else
                return true;
        }
    };

  • 0
    L
    class Solution {
    public:
        bool isPowerOfFour(int num) {
            if (num & (num - 1))
                return false;
            if (num & 0x55555555)
                return true;
            return false;
        }
    };
    

    This code segment is apparently better than three if statements.

    But Why this code need 8ms to run, which is slower than above ?


Log in to reply
 

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