标签:
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.
这道题是计算一个数是否是2的次方数,其实可以转化为计算这个数的二进制位上有多少个1,就可以了,儿这个可以采用位运算的方法,即用一个数n和n-1位与运算,就可以去掉一个1了,
在这里需要注意的是负数一定不是2的次方。
#include<iostream>
using namespace std;
bool isPowerOfTwo(int n) {
if(n<0)
return 0;
int re=0;
while(n)
{
re++;
n=n&(n-1);
}
if(re==1)
return 1;
else
return 0;
}
int main()
{
cout<<isPowerOfTwo(6)<<endl;
}
leetcode_231题——Power of Two (位运算)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4658918.html