Given an integer, write a function to determine if it is a power of two.
这道题让我们判断一个数是否为2的次方数,而且要求时间和空间复杂度都为常数,那么对于这种玩数字的题,我们应该首先考虑位操作 Bit Operation。在LeetCode中,位操作的题有很多,比如比如Repeated DNA Sequences 求重复的DNA序列, Single Number 单独的数字, Single Number II 单独的数字之二 , Grey Code 格雷码, Reverse Bits 翻转位,Bitwise AND of Numbers Range 数字范围位相与,Number of 1 Bits 位1的个数和 Divide Two Integers 两数相除等等。那么我们来观察下2的次方数的二进制写法的特点:
1 2 4 8 16 ....
1 10 100 1000 10000 ....
那么我们很容易看出来2的次方数都只有一个1,剩下的都是0,所以我们的解题思路就有了,我们只要每次判断最低位是否为1,然后向右移位,最后统计1的个数即可判断是否是2的次方数,代码如下:
解法一:
public class Solution { public boolean isPowerOfTwo(int n) { return n>0 && Integer.bitCount(n) == 1; } }
这道题还有一个技巧,如果一个数是2的次方数的话,根据上面分析,那么它的二进数必然是最高位为1,其它都为0,那么如果此时我们减1的话,则最高位会降一位,其余为0的位现在都为变为1,那么我们把两数相与,就会得到0,用这个性质也能来解题,而且只需一行代码就可以搞定,如下所示:
This question is not an difficult one, and there are many ways to solve it.
Method 1: Iterative
check if n can be divided by 2. If yes, divide n by 2 and check it repeatedly.
if(n==0) return false;
while(n%2==0) n/=2;
return (n==1);
Time complexity = O(log n)
Method 2: Recursive
return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));
Time complexity = O(log n)
Method 3: Bit operation
If n is the power of two:
- n = 2 ^ 0 = 1 = 0b0000...00000001, and (n - 1) = 0 = 0b0000...0000.
- n = 2 ^ 1 = 2 = 0b0000...00000010, and (n - 1) = 1 = 0b0000...0001.
- n = 2 ^ 2 = 4 = 0b0000...00000100, and (n - 1) = 3 = 0b0000...0011.
- n = 2 ^ 3 = 8 = 0b0000...00001000, and (n - 1) = 7 = 0b0000...0111.
we have n & (n-1) == 0b0000...0000 == 0
Otherwise, n & (n-1) != 0.
For example, n =14 = 0b0000...1110, and (n - 1) = 13 = 0b0000...1101.
return n>0 && ((n & (n-1)) == 0);
Time complexity = O(1)
Method 4: Math derivation
Because the range of an integer = -2147483648 (-2^31) ~ 2147483647 (2^31-1), the max possible power of two = 2^30 = 1073741824.
(1) If n is the power of two, let n = 2^k, where k is an integer.
We have 2^30 = (2^k) * 2^(30-k), which means (2^30 % 2^k) == 0.
(2) If n is not the power of two, let n = j*(2^k), where k is an integer and j is an odd number.
We have (2^30 % j*(2^k)) == (2^(30-k) % j) != 0.
return n>0 && (1073741824 % n == 0);
Time complexity = O(1)