在这里,我们将看到,如果我们可以将一个数字表示为2的两个非零幂的和,那么我们将检查给定的数字N是否可以表示为(2 x + 2 y),其中x,y> 0。数字是10,可以表示为2 3 + 2 1。
该方法很简单。有两种情况。如果数字n是偶数,则可以表示为2x。其中x>0。另一种情况是N是奇数,因此它永远不能表示为2的幂的和。我们不能将power用作0,因此无法获得奇数。对于其二进制表示形式的所有奇数LSb为1
#include <iostream> using namespace std; bool isSumofTwosPower(int n) { if((n & 1) == 0){ return true; } else { return false; } } int main() { int num = 86; if(isSumofTwosPower(num)){ cout << "Can be represented"; } else { cout << "Cannot be represented"; } }
输出结果
Can be represented