Last updated 6 years ago
Was this helpful?
Given an integer, write a function to determine if it is a power of two.
如果是2的power, 那么2进制下所有数中只有1位是1, 其余都是0. N - 1会除了N的1那位是0外全部都是0. 因此它们相与定会是0.
class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } }
时间复杂度O(1).