Power of Two

来源:互联网 发布:linux oracle安装教程 编辑:程序博客网 时间:2024/05/16 23:41

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

题目解析:

求一个数是否是2的幂次方所得。是就返回true,不是就返回false.

方法一:

直接用n%2,结果如果为1,就返回false(n=1除外,因为2的0次幂为1)。

代码如下:

class Solution {public:    bool isPowerOfTwo(int n) {        if(n<=0) return false;        while(n)        {            if(n%2==1&&n!=1) return false;            n/=2;        }        return true;            }};

方法二:

如果某个值是2的幂次方所得,其对应二进制则是最高位为1,其余位为0.n-1则相反,除了最高位,其余比特位均为1.则我们可以判断n&(n-1)是否等于0来判断n是否是2的幂次方值。代码如下:

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



0 0
原创粉丝点击