Challenge - 5 Problems
Bitwise Even-Odd Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this C++ code snippet?
Consider the following code that checks if a number is even or odd using bitwise operations. What will it print?
DSA C++
#include <iostream> int main() { int num = 7; if (num & 1) { std::cout << "Odd" << std::endl; } else { std::cout << "Even" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
The bitwise AND with 1 checks the least significant bit of the number.
✗ Incorrect
The expression 'num & 1' checks if the least significant bit is 1, which means the number is odd. Since 7 in binary ends with 1, it prints "Odd".
❓ Predict Output
intermediateWhat is the output when num = 12?
Using the same logic as before, what will the program print if num is 12?
DSA C++
#include <iostream> int main() { int num = 12; if (num & 1) { std::cout << "Odd" << std::endl; } else { std::cout << "Even" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Check the least significant bit of 12 in binary.
✗ Incorrect
12 in binary ends with 0, so 12 & 1 equals 0, which means the number is even.
🧠 Conceptual
advancedWhy does using bitwise AND with 1 check if a number is even or odd?
Select the best explanation for why the expression (num & 1) can determine if num is even or odd.
Attempts:
2 left
💡 Hint
Think about binary representation of even and odd numbers.
✗ Incorrect
In binary, odd numbers always have the last bit set to 1, while even numbers have it set to 0. The bitwise AND with 1 isolates this bit.
🔧 Debug
advancedDoes this code work correctly?
Examine this code snippet that attempts to check if a number is even or odd using bits. Select the correct statement.
DSA C++
#include <iostream> int main() { int num = 5; if (num & 1 == 1) { std::cout << "Odd" << std::endl; } else { std::cout << "Even" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Check operator precedence between & and == operators. Which has higher precedence?
✗ Incorrect
Operator precedence in C++: the equality operator (==) has higher precedence than bitwise AND (&). Therefore, 'num & 1 == 1' is parsed as 'num & (1 == 1)'. Since 1 == 1 is true (which is 1), it becomes 'num & 1', which correctly checks if the number is odd. There is no error.
❓ Predict Output
expertWhat is the output of this code with negative number?
What will this program print when num = -3?
DSA C++
#include <iostream> int main() { int num = -3; if (num & 1) { std::cout << "Odd" << std::endl; } else { std::cout << "Even" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Consider how negative numbers are represented in two's complement.
✗ Incorrect
In two's complement, negative odd numbers still have the least significant bit set to 1, so the bitwise AND with 1 returns 1, indicating odd.
