Power of four by binary representation observation in java


  • 0
    A

    By simple observation of bit sets from 4^2, 4^3, 4^4 ,.. => 2^4, 2^6, 2^8,...

    public boolean isPowerOfFour(int num) {
            if( num == 1 || num == 4) return true;
            // almost like power of 2 problem
            // exactly one bit should be enables and also enabled bit should be either 4 or 6 or 8 etc..
            
            int position = 0;
            int noOfBitsEnabled = 0;
            int enabledPoistion = -1;
            while( num > 0){
                noOfBitsEnabled +=  (num & 1);
                enabledPoistion = position;
                num >>=  1;
                position++;
            }
            
            // 4^0 and 4^1 are already handled with initila conditions
            // 4^2, 4^3, 4^4 etc => 2^4, 2^6, 2^8 ... so enabled postion should be even and >= 4...
            return ((noOfBitsEnabled == 1) && (enabledPoistion %2 == 0 && enabledPoistion >= 4));
        }
    

Log in to reply
 

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