Skip to main content

Power Of 2

Problem​

Given a non-negative integer n. The task is to check if it is a power of 2.

Examples:​

Example 1:

Input: n = 8
Output: true
Explanation: 8 is equal to 2 raised to 3 (2^3 = 8).

Example 2:

Input: n = 98
Output: false
Explanation: 98 cannot be obtained by any power of 2.

Example 3:

Input: n = 1
Output: true
Explanation: (2^0 = 1).
  • Expected Time Complexity: O(logn)O(log n)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

0≤n<10200 ≤ n < 10^{20}

Solution​

Python

def isPowerofTwo(self,n : int ) -> bool:
if (n == 0):
return False
while (n != 1):
if (n % 2 != 0):
return False
n = n // 2
return True

Java

public static boolean isPowerofTwo(long n) {
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}

C

bool isPowerofTwo(long long n) {
if (n == 0)
return 0;
while (n != 1) {
if (n % 2 != 0)
return 0;
n = n / 2;
}
return 1;
}

C++

bool isPowerofTwo(long long n) {
if (n == 0)
return 0;
while (n != 1) {
if (n % 2 != 0)
return 0;
n = n / 2;
}
return 1;
}
  • Time Complexity: O(logn)O(log n)
  • Auxiliary Space: O(1)O(1)