Is Power of Two
Definition​
- Definition
- Explanation
- Guidance
- Tips
The Power of Two Algorithm determines whether a given integer is a power of two. It leverages bitwise operations for efficiency and simplicity
Performing a bitwise AND operation between the integer and its decrement (integer - 1). If the result is zero, the integer is a power of two
- Check if the given integer is less than or equal to
0
- Perform a bitwise
AND
operation between the integer and its decrement (integer - 1
) - If the result is
0
, returntrue
- Otherwise, return false
- utilize bitwise operations for efficient manipulation of bits
- avoid iterative approaches; the algorithm can be solved in constant time
Practice​
- Practice
- Solution
isPowerOfTwo(x):
if x <= 0:
return false
return (x & (x - 1)) == 0
package main
func isPowerOfTwoNaive(n int) bool {
if n <= 0 {
return false
}
for n%2 == 0 {
n /= 2
}
return n == 1
}
func isPowerOfTwoBitwise(n int) bool {
return n > 0 && (n&(n-1)) == 0
}
public class Main {
public static boolean isPowerOfTwoNaive(int n) {
if (n <= 0) {
return false;
}
while (n % 2 == 0) {
n /= 2;
}
return n == 1;
}
public static boolean isPowerOfTwoBitwise(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
function isPowerOfTwoNaive(n) {
if (n <= 0) {
return false;
}
while (n % 2 === 0) {
n /= 2;
}
return n === 1;
}
function isPowerOfTwoBitwise(n) {
return n > 0 && (n & (n - 1)) === 0;
}
fun isPowerOfTwoNaive(n: Int): Boolean {
var num = n
if (num <= 0)
return false
while (num % 2 == 0) {
num /= 2
}
return num == 1
}
fun isPowerOfTwoBitwise(n: Int): Boolean {
return n > 0 && (n and (n - 1)) == 0
}
def is_power_of_two_naive(n):
if n <= 0:
return False
while n % 2 == 0:
n //= 2
return n == 1
def is_power_of_two_bitwise(n):
return n > 0 and (n & (n - 1)) == 0
fn is_power_of_two_naive(mut n: i32) -> bool {
if n <= 0 {
return false;
}
while n % 2 == 0 {
n /= 2;
}
n == 1
}
fn is_power_of_two_bitwise(n: i32) -> bool {
n > 0 && (n & (n - 1)) == 0
}
function isPowerOfTwoNaive(n: number): boolean {
if (n <= 0) return false;
while (n % 2 === 0) {
n /= 2;
}
return n === 1;
}
function isPowerOfTwoBitwise(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}