C++ solution, short and clean.


  • 1
    S

    My solution first make an integer by setting every bit of power of 4 to 1. Then we check if the num is an power of 2, and also see if it has a '1' position different to the bit position possible for power of 4.

    class Solution {
    public:
        bool isPowerOfFour(int num) {
            // Mark every possible '1' position in the integer.
            int max1 = 1431655765; //0b1010101010101010101010101010101
    
            int max2 = (1 << 30);
            // 1) check if num is a power of 2
            // 2) check if num's '1' position changes any '0' in max1 to '1'.
            if (num > 0 && (max2 % num == 0) && ((max1 | num) == max1)) return true;
            return false;
        }
    };

Log in to reply
 

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