2016年2月11日 星期四

LEET code -- Power of Two

Given an integer, write a function to determine if it is a power of two.

神解法
因為二的倍數依樣只會有1個bit   如果跟n-1 做and一定0

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;
}
}



1
2
3
4
5
bool isPowerOfTwo(int n) {
    if(n<=0)return false;
    while(n%2==0)n/=2;
    return n==1? true:false;
}

沒有留言:

張貼留言