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 integer value 8 (binary 1000), what is the output after setting the 3rd bit (0-based from right)?
DSA Java
int num = 8; int bitPosition = 3; int result = num | (1 << bitPosition); System.out.println(result);
Attempts:
2 left
💡 Hint
Remember that setting a bit means making sure that bit is 1 using OR operation.
✗ Incorrect
The number 8 in binary is 1000. The 3rd bit (0-based) is already set (1). Setting it again keeps the number unchanged, so the output is 8.
❓ Predict Output
intermediateWhat is the output after clearing the 2nd bit?
Given the integer value 14 (binary 1110), what is the output after clearing the 2nd bit (0-based from right)?
DSA Java
int num = 14; int bitPosition = 2; int result = num & ~(1 << bitPosition); System.out.println(result);
Attempts:
2 left
💡 Hint
Clearing a bit means making that bit 0 using AND with NOT mask.
✗ Incorrect
14 in binary is 1110. Clearing the 2nd bit (counting from 0) changes the bit from 1 to 0, resulting in 1010 binary which is 10 decimal.
❓ Predict Output
advancedWhat is the output after toggling the 1st bit?
Given the integer value 5 (binary 0101), what is the output after toggling the 1st bit (0-based from right)?
DSA Java
int num = 5; int bitPosition = 1; int result = num ^ (1 << bitPosition); System.out.println(result);
Attempts:
2 left
💡 Hint
Toggling flips the bit: 0 becomes 1, 1 becomes 0 using XOR.
✗ Incorrect
5 in binary is 0101. Toggling the 1st bit flips it from 0 to 1, resulting in 0111 binary which is 7 decimal.
🧠 Conceptual
advancedWhich operation clears a specific bit at position k?
Which bitwise operation correctly clears the bit at position k (0-based from right) in integer n?
Attempts:
2 left
💡 Hint
Clearing means setting the bit to 0 without affecting others.
✗ Incorrect
To clear a bit, use AND with the complement of the bit mask. This sets the target bit to 0 and leaves others unchanged.
🔧 Debug
expertWhy does this toggle bit code fail for negative numbers?
Consider this code to toggle the 4th bit of an integer n:
int result = n ^ (1 << 4);
Why might this code produce unexpected results when n is negative?
DSA Java
int n = -16; int result = n ^ (1 << 4); System.out.println(result);
Attempts:
2 left
💡 Hint
Think about how negative numbers are stored and how toggling bits affects sign.
✗ Incorrect
Negative numbers use two's complement. Toggling bit 4 may flip the sign bit or change the number's sign unexpectedly.
