Share my solution in Java using bit manipulation


  • 4
    I
    public class Solution {
        public boolean isPowerOfFour(int n) {
            if (n <= 0 || (n & n - 1) != 0) return false;
            return (n & 0x55555555) != 0;
        }
    }
    

    first, the number must be power of two. using (n & n - 1) to count 1s in binary string.

    Secondly, we must make sure that the only bit 1 appears at some odd position. So using a mask 0x55555555.


  • 0
    M

    thank you this is a good solution.


Log in to reply
 

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