An alternative to 0x55555555 in Java without loop


  • 0
    A

    An alternative way to exclude powers of 2 but not powers of 4 is by & with number 715827882. In binary representation, this is the number 101010...10 with 15 copies of 10. So it has all 1's on the even position of the 31 positions. A power of 4 should have its 1 on the odd position thus is 0 after & with 715827882.

    class Solution {
        private int n = 715827882;
        public boolean isPowerOfFour(int num) {
            if (num <= 0) {
                return false;
            }
            if ((num & (num - 1)) != 0) {
                return false;
            }
            int bits = 0; 
            return (num & n) == 0;
        }
    }
    

Log in to reply
 

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