1. 程式人生 > >LeetCode(231) Power of Two

LeetCode(231) Power of Two

題目

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;
}