One line Java method costs 2ms


  • 4
    S

    Note that 2^n = 00..100..0
    and 2^n-1 = 00...011..1
    so 2^n & 2^n-1 = 0

    public class PowerofTwo {

    public static boolean isPowerOfTwo(int n) {
    	return n < 1 ? false : (n & (n - 1)) == 0 ? true : false;
    }
    

    }


Log in to reply
 

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