Skip to content

Latest commit

 

History

History
14 lines (10 loc) · 500 Bytes

231.2的幂.md

File metadata and controls

14 lines (10 loc) · 500 Bytes

231.2的幂

思路:一个数 n 是 2 的幂,当且仅当 n 是正整数,并且 n 的二进制仅包含 1个1,且在最高位

技巧:n和n-1按位与,结果为0即是2的幂,如8的二进制1000,与7的二进制0111,按位与结果为0000

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n <= 0 : return False
        return n & (n-1) == 0