Java Code using bit manipulation


  • 0
    K

    If the number is a multiple of four, then the only 1 int its binary representation should be in position of 1,3,5... when you count from right.
    I have used that logic here.
    The if( (n & (n-1)) !=0) return false; checks if it is a multiple of two or not.
    Inspired by the solutions of Power of Two Problem.

    int n=num;
            if(n==1) return true;
            if( (n & (n-1)) !=0) return false;
            else{
                while(n!=0){
                    n=n>>>2;
                    if(n==1) return true;
                }
                return false;
            }
    

Log in to reply
 

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