leetcode刷题笔记231 2的幂

题目描述:

给定一个整数,写一个函数来判断它是否是2的幂。

题目分析:

判断一个整数是不是2的幂,可根据二进制来分析。2的幂如2,4,8,等有一个特点:

二进制数首位为1,其他位为0,如2为10,4为100

2&(2-1)=0   4&(4-1)=0 

即得出结论如果一个数n为2的幂,则n(n-1)=0

此题通过率37.6%,挺高的

解答代码:

C++版:

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

Python版:

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n<=0:
            return False
        return ((n & (n-1))==0)
Code
原文地址:https://www.cnblogs.com/qflyue/p/8973054.html