Complete the code to check if a number is a power of two using bitwise AND.
func isPowerOfTwo(n int) bool {
return n > 0 && (n & [1]) == 0
}The expression n & (n-1) clears the lowest set bit. If the result is zero, n is a power of two.
Complete the code to return false immediately if the number is not positive.
func isPowerOfTwo(n int) bool {
if [1] {
return false
}
return (n & (n - 1)) == 0
}Numbers less than or equal to zero cannot be powers of two, so we return false for n <= 0.
Fix the error in the bitwise check to correctly identify powers of two.
func isPowerOfTwo(n int) bool {
if n <= 0 {
return false
}
return (n [1] (n - 1)) == 0
}The bitwise AND operator & is used to check if n is a power of two by clearing the lowest set bit.
Fill both blanks to complete the function that returns true if n is a power of two.
func isPowerOfTwo(n int) bool {
if n [1] 0 {
return false
}
return (n & (n [2] 1)) == 0
}The function first checks if n is less than or equal to zero, then uses n & (n - 1) to check if n is a power of two.
Fill all three blanks to create a map of numbers to booleans indicating if they are powers of two.
func powersMap(nums []int) map[int]bool {
result := make(map[int]bool)
for _, [1] := range nums {
if [2] <= 0 {
result[[3]] = false
} else {
result[[3]] = ([2] & ([2] - 1)) == 0
}
}
return result
}The loop variable is num. We check if num is positive and then use the bitwise check to set the map value.
