Java simple code (without using loops)


  • 0
    A
    public class Solution {
        public boolean isPowerOfFour(int n) {
            if(n<1) return false;
            int root = (int)Math.sqrt(n);
            return (n&(n-1))==0 && n-root*root==0;
        }
    }
    

  • 0
    8

    can u explain it?thx


  • 2
    J

    The key is to observe that (n & (n-1) == 0) is true for all n that are factor of 2. I think the following variant is a bit more intuitive because it basically checks that the sqrt of the given number n is a factor of 2 and that that sqrt*sqrt = the given number

        public boolean isPowerOfFour(int n) {
            if(n<1) return false;
            int root = (int)Math.sqrt(n);
            return (root&(root-1))==0 && root*root==n;
        }
    }

Log in to reply
 

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