231. Power of Two

来源:互联网 发布:阿里云先知大会 编辑:程序博客网 时间:2024/06/14 15:40

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

多种解法,可以按之前求isPowerofThree的,也可以考虑PowerofTwo的独特性质,即只有一个位上为1,所以n&(n-1)=0.

class Solution {public:    bool isPowerOfTwo(int n) {        if(n<=0)        {            return false;        }        if((n&(n-1)) == 0)        //or if(n == pow(2, round(log(n)/log(2))))        {            return true;        }        return false;    }};
0 0
原创粉丝点击