Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a number is a power of two using bitwise AND.
DSA Javascript
function isPowerOfTwo(n) {
return n > 0 && (n & (n [1] 1)) === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction.
Using bitwise OR instead of AND.
✗ Incorrect
The expression n & (n - 1) checks if n is a power of two by clearing the lowest set bit. If the result is zero, n is a power of two.
2fill in blank
mediumComplete the code to return false for non-positive numbers.
DSA Javascript
function isPowerOfTwo(n) {
if (n [1] 0) return false;
return (n & (n - 1)) === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using equality check instead of less than or equal to.
Using greater than or equal to.
✗ Incorrect
Numbers less than or equal to zero cannot be powers of two. Using n <= 0 excludes zero and negative numbers.
3fill in blank
hardFix the error in the bitwise check to correctly identify power of two.
DSA Javascript
function isPowerOfTwo(n) {
return n > 0 && (n & (n [1] 1)) === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction.
Using bitwise OR or AND incorrectly.
✗ Incorrect
The correct operation is n & (n - 1). Using subtraction clears the lowest set bit to check power of two.
4fill in blank
hardFill both blanks to complete the function that returns true if n is a power of two and false otherwise.
DSA Javascript
function isPowerOfTwo(n) {
if (n [1] 0) return false;
return (n & (n [2] 1)) === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction.
Using greater than or equal to in the first check.
✗ Incorrect
First, check if n is less than or equal to zero to exclude invalid inputs. Then use n & (n - 1) to check power of two.
5fill in blank
hardFill all three blanks to create a function that returns true if n is a power of two, false otherwise, and handles zero and negative inputs.
DSA Javascript
function isPowerOfTwo(n) {
if (n [1] 0) return false;
return (n [2] (n [3] 1)) === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of <= in the first check.
Using + instead of - in the subtraction.
Using | instead of & for bitwise operation.
✗ Incorrect
Check if n is less than or equal to zero to exclude invalid inputs. Then use bitwise AND between n and (n - 1) to check power of two.
