Algorithm
Problem Name: 231. Power of Two
Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
Example 1:
Input: n = 1 Output: true Explanation: 20 = 1
Example 2:
Input: n = 16 Output: true Explanation: 24 = 16
Example 3:
Input: n = 3 Output: false
Constraints:
-231 <= n <= 231 - 1
Code Examples
#1 Code Example with C Programming
Code -
C Programming
bool isPowerOfTwo(int n) {
if (!n || (n & 0x80000000)) return false; // this is important!
#if 0
while (!(n & 1)) n >>= 1;
return n == 1 ? true : false;
#else
//printf("%x, %x\n", n, n - 1);
return (n & (n - 1)) == 0 ? true : false;
#endif
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public boolean isPowerOfTwo(int n) {
if (n > 1 && n % 2 != 0) {
return false;
}
int start = 0;
int end = n / 2;
while (start < = end) {
int mid = (start + end) / 2;
int pow = (int) Math.pow(2, mid);
if (pow == n) {
return true;
} else if (pow > n) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
const isPowerOfTwo = function(n) {
let tmp = 0
let idx = 0
while(tmp <= n) {
if((tmp = Math.pow(2, idx)) === n) {
return true
} else {
idx += 1
}
}
return false
};
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
i=0
while 2**i<=n:
if 2**i==n: return True
i+=1
return False
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0231_PowerOfTwo
{
public bool IsPowerOfTwo(int n)
{
if (n == 0) return false;
long x = n;
return (x & -x) == x;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output