Tuesday, September 5, 2017

342. Power of Four

https://leetcode.com/problems/power-of-four/description/
Solution 1. Shift and compare the last 2 bits on the left.
    bool isPowerOfFour(int num) {
        if(num<=0) return false;    
        while(num){
            if(num&3) {
                if(num == 1) return true;
                return false;
            }
            num >>= 2;
        }
        return true;
    }
Solution 2. It can be fit in one line. A number is power of 4 only if num>4 and only 1 nonzero bit and the nonzero bit is at 1, or 3, or 5 ...
    bool isPowerOfFour(int num) {
        return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
    }

No comments:

Post a Comment