【Power of Two】cpp

时间:2021-12-13 06:41:51

题目:

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

代码:

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

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<= ? false : !(n & (n-));
}
};