给定一个整数N ,任务是检查N是否可以表示为2的幂之和,其中所有幂> 0,即2 0不能加和。
例子:
Input: N = 10
Output: 1
23 + 21 = 10
Input: N = 9
Output: 0
方法:有两种情况:
- 当N为偶数时,当幂> 0时,它总是可以表示为2的幂之和。
- 当N为奇数时,如果总和中不包括2 0,则它永远不能表示为2的幂的和。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that return true if n
// can be represented as the sum
// of powers of 2 without using 2^0
bool isSumOfPowersOfTwo(int n)
{
if (n % 2 == 1)
return false;
else
return true;
}
// Driver code
int main()
{
int n = 10;
if (isSumOfPowersOfTwo(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function that return true if n
// can be represented as the sum
// of powers of 2 without using 2^0
static boolean isSumOfPowersOfTwo(int n)
{
if (n % 2 == 1)
return false;
else
return true;
}
// Driver code
public static void main(String args[])
{
int n = 10;
if (isSumOfPowersOfTwo(n))
System.out.print("Yes");
else
System.out.print("No");
}
}
Python3
# Python3 implementation of the approach
# Function that return true if n
# can be represented as the sum
# of powers of 2 without using 2^0
def isSumOfPowersOfTwo(n):
if n % 2 == 1:
return False
else:
return True
# Driver code
n = 10
if isSumOfPowersOfTwo(n):
print("Yes")
else:
print("No")
# This code is contributed
# by Shrikant13
C#
// C# implementation of the approach
using System;
class GFG {
// Function that return true if n
// can be represented as the sum
// of powers of 2 without using 2^0
static bool isSumOfPowersOfTwo(int n)
{
if (n % 2 == 1)
return false;
else
return true;
}
// Driver code
public static void Main()
{
int n = 10;
if (isSumOfPowersOfTwo(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
PHP
Javascript
输出:
Yes
时间复杂度: O(1)