您的位置:首页 > 编程语言 > C语言/C++

【Power of Two】cpp

2015-07-22 07:23 239 查看
题目:

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

代码:

class Solution {
public:
bool isPowerOfTwo(int n) {
if ( n<=0 ) return false;
int countOne = 0;
for ( int i=0; i<sizeof(n)*8 && countOne<=1; ++i )
{
countOne += (n>>i) & 1;
}
return countOne==1;
}
};


tips:

首先的思路是bit-munipulation

检查int中有多少个1

学习了一个更简洁的(https://leetcode.com/discuss/45017/5-lines-o-1-space%26time-c-solution-no-hash

自己优化了一下 一行代码AC。

class Solution {
public:
bool isPowerOfTwo(int n) {
return  n<=0 ? false : !(n & (n-1));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: