Challenge - 5 Problems
Bitwise Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after setting the 3rd bit?
Given the code below, what will be the printed value of
num after setting the 3rd bit (0-based index from right)?DSA C++
int num = 8; // binary 1000 int pos = 3; num = num | (1 << pos); std::cout << num << std::endl;
Attempts:
2 left
💡 Hint
Remember that bits are counted from 0 starting at the rightmost bit.
✗ Incorrect
The 3rd bit (0-based) corresponds to the 8's place. Since num is already 8 (1000), setting the 3rd bit again keeps it 8.
❓ Predict Output
intermediateWhat is the output after clearing the 1st bit?
What will be the output after clearing the 1st bit (0-based) of
num?DSA C++
int num = 11; // binary 1011 int pos = 1; num = num & ~(1 << pos); std::cout << num << std::endl;
Attempts:
2 left
💡 Hint
Clearing a bit means setting it to 0.
✗ Incorrect
The 1st bit of 1011 is 1. Clearing it changes 1011 to 1001 which is 9.
❓ Predict Output
advancedWhat is the output after toggling the 2nd bit?
Given the code below, what will be the output after toggling the 2nd bit (0-based) of
num?DSA C++
int num = 13; // binary 1101 int pos = 2; num = num ^ (1 << pos); std::cout << num << std::endl;
Attempts:
2 left
💡 Hint
Toggling flips the bit: 0 becomes 1, 1 becomes 0.
✗ Incorrect
The 2nd bit of 1101 is 1. Toggling it changes 1101 to 1001 which is 9.
🔧 Debug
advancedIdentify the error in clearing a bit code
The following code is intended to clear the 4th bit of
num. What error will it cause?DSA C++
int num = 31; // binary 11111 int pos = 4; num = num & (1 << ~pos); std::cout << num << std::endl;
Attempts:
2 left
💡 Hint
Check the operator precedence and bitwise NOT usage.
✗ Incorrect
The expression (1 << ~pos) shifts 1 by a negative number (since ~4 = -5), which is undefined behavior and results in wrong output 15 instead of clearing bit 4.
🧠 Conceptual
expertHow many bits are set after toggling bits 0, 1, and 2 of 0?
Starting with
num = 0, you toggle bits at positions 0, 1, and 2 (0-based). How many bits are set in num after these operations?DSA C++
int num = 0; num = num ^ (1 << 0); num = num ^ (1 << 1); num = num ^ (1 << 2);
Attempts:
2 left
💡 Hint
Toggling a bit from 0 sets it to 1.
✗ Incorrect
Toggling bits 0,1,2 from 0 sets all three bits to 1, so 3 bits are set.
