2016/4/22

【LeetCode 231】Power of Two

LeetCode 231: Power of Two
Question: Given an integer, write a function to determine if it is a power of two.

1
2
3
bool isPowerOfTwo(int n) {

}

Solution

1
2
3
bool isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

解析
在二進位中,只有出現一次1即為2的冪次方
0001 => 1
0010 => 2
0100 => 4
1000 => 8
因此可用bit operator判斷完成題目要求
(n & (n -1)) == 0
描述式採用進位特性,來消除最低位的1,執行一次後若數值為0則表示只有一個1,因此可以判斷為2的冪次
考量題目框架帶入的參數值是帶有正負號的int型別,所以要多判斷數值是否大於0