LeetCode(231) Power of Two

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fly_yr/article/details/52356691

题目

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

分析

判断给定整数是否为2的整次幂。
当该整数对应的二进制串中只有1位1时,必然为2的整次幂。
只需判断n&(n-1)是否为0即可。

代码

#include <iostream>
#include <cstdlib>

using namespace std;

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

int main()
{
	cout << Solution().isPowerOfTwo(2) << endl;

	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/fly_yr/article/details/52356691