231. Power of Two

时间:2021-10-08 15:03:34

题目:

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

链接: http://leetcode.com/problems/power-of-two/

题解:

验证一个数是否是2的幂次,我们可以使用(n & (n - 1))来决定。 比如 10 & 01, 100 & 011等等。

Time Complexity - O(1), Space Complexity - O(1)

public class Solution {
public boolean isPowerOfTwo(int n) {
if(n <= 0)
return 0;
return (n & (n - 1) == 0);
}
}

二刷:

二的幂有一个特点,就是整个数字里只有一个比特位为1,其余都是0, 我们可以count有几个比特位为1,大于1的话结果为false,等于1的话为true

Java:

Time Complexity - O(1), Space Complexity - O(1)

public class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 1) {
return false;
}
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count == 1;
}
}

更简练的写法 - 因为2的幂次只有一个比特位为1,那么我们用n & (n - 1)将其清零后,得到的结果应该是0。

public class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 1) {
return false;
}
return (n & (n - 1)) == 0;
}
}

Reference:

https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2