Power of Two ----- 判断一个数是不是2的幂

来源:互联网 发布:方正字体投诉淘宝店铺 编辑:程序博客网 时间:2024/04/27 16:18

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating

all test cases.

Subscribe to see which companies asked this question


分析:

这里的题意是求解一个数n是不是2的幂。


这里我使用位运算来求解。


详解:

点击打开链接

方法一:


<pre name="code" class="html">class Solution {public:    bool isPowerOfTwo(int n) {        return (n>0) && (!(n&(n-1)));    }};

方法二:

class Solution {public:   bool isPowerOfTwo(int n) {        int count = 0;        while (n > 0)        {            count+=(n&0x01);            n>>=1;        }        return count==1;    }}};


0 0
原创粉丝点击