Four C++ Solutions


  • 4
    G

    Method 1:

    class Solution {
    public:
        bool isPowerOfFour(int num) {
            while (num && (num % 4 == 0)) {
                num /= 4;
            }
            return num == 1;
        }
    };
    

    Method 2:

    class Solution {
    public:
        bool isPowerOfFour(int num) {
            return num > 0 && int(log10(num) / log10(4)) - log10(num) / log10(4) == 0;
        }
    };
    

    Method 3:

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

    Method 4:

    class Solution {
    public:
        bool isPowerOfFour(int num) {
            return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0;
        }
    };

Log in to reply
 

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