Complete the code to check if a number is a power of two using bitwise AND.
bool IsPowerOfTwo(int n) {
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 check if a number is a power of two using a loop.
bool IsPowerOfTwo(int n) {
if (n <= 0) return false;
while (n != 1) {
if (n % [1] != 0) return false;
n /= 2;
}
return true;
}To be a power of two, the number must be divisible by 2 repeatedly until it becomes 1.
Fix the error in the code to correctly check if a number is a power of two.
bool IsPowerOfTwo(int n) {
return n > 0 && (n & [1]) == 0;
}The correct check is (n & (n - 1)) == 0.
Fill both blanks to create a dictionary comprehension that maps numbers to True if they are powers of two.
var powers = new Dictionary<int, bool> {
{ [1], [2] }
};The dictionary maps the number 1 to true because 1 is a power of two.
Fill all three blanks to create a LINQ expression that filters powers of two from a list.
var powersOfTwo = numbers.Where(n => n > 0 && (n & [1]) == [2]).ToList(); // Print results powersOfTwo.ForEach(n => Console.WriteLine(n[3]));
The LINQ filters numbers where n & (n - 1) == 0. The print adds a message after the number.
