Power of Two

https://leetcode.com/problems/power-of-two/description/

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

Thoughts

如果是2的power, 那么2进制下所有数中只有1位是1, 其余都是0. N - 1会除了N的1那位是0外全部都是0. 因此它们相与定会是0.

Code

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

Analysis

时间复杂度O(1).

Last updated