Challenge - 5 Problems
Power of Two Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Power of Two Check Function
What is the output of the following Go code that checks if a number is a power of two?
DSA Go
package main import "fmt" func isPowerOfTwo(n int) bool { return n > 0 && (n&(n-1)) == 0 } func main() { fmt.Println(isPowerOfTwo(16)) fmt.Println(isPowerOfTwo(18)) }
Attempts:
2 left
💡 Hint
Remember that a power of two has only one bit set in binary.
✗ Incorrect
The function returns true only if n is greater than zero and n & (n-1) equals zero, which is true only for powers of two.
🧠 Conceptual
intermediateUnderstanding Bitwise Check for Power of Two
Why does the expression (n & (n-1)) == 0 check if n is a power of two?
Attempts:
2 left
💡 Hint
Think about binary representation of powers of two and what subtracting 1 does.
✗ Incorrect
A power of two has only one '1' bit. Subtracting 1 flips that bit and all bits after it, so ANDing n and n-1 clears the only set bit, resulting in zero.
🔧 Debug
advancedIdentify the Error in Power of Two Check
What error does the following Go code produce when checking if a number is a power of two?
DSA Go
package main import "fmt" func isPowerOfTwo(n int) bool { return n&(n-1) == 0 } func main() { fmt.Println(isPowerOfTwo(0)) }
Attempts:
2 left
💡 Hint
Consider what happens when n is zero in the expression.
✗ Incorrect
The function returns true for 0 because 0 & (0-1) equals 0, but zero is not a power of two. The check should include n > 0.
🚀 Application
advancedCount Powers of Two in a List
Given a list of integers, which Go code correctly counts how many numbers are powers of two?
DSA Go
package main import "fmt" func isPowerOfTwo(n int) bool { return n > 0 && (n&(n-1)) == 0 } func main() { nums := []int{1, 2, 3, 4, 5, 8, 16, 18} count := 0 // Fill in counting logic here fmt.Println(count) }
Attempts:
2 left
💡 Hint
Use the provided isPowerOfTwo function correctly to count.
✗ Incorrect
Option D correctly iterates over nums, uses isPowerOfTwo, and increments count. Option D adds values instead of count. Option D misses n > 0 check. Option D counts all positive numbers.
🧠 Conceptual
expertWhy is Zero Not a Power of Two?
Why is zero (0) not considered a power of two in computer science?
Attempts:
2 left
💡 Hint
Think about the mathematical definition of powers of two.
✗ Incorrect
Powers of two are numbers like 1, 2, 4, 8, ... which are 2 raised to some exponent. Zero is not in this sequence.
