Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to set the 3rd bit of number n.
DSA Javascript
let n = 8; // 1000 in binary let bitPosition = 3; n = n | (1 << [1]); console.log(n.toString(2));
Attempts:
3 left
💡 Hint
Common Mistakes
Using 3 instead of 2 for bit position
Forgetting zero-based indexing
✗ Incorrect
Bits are zero-indexed from the right, so the 3rd bit means position 2.
2fill in blank
mediumComplete the code to clear the 2nd bit of number n.
DSA Javascript
let n = 14; // 1110 in binary let bitPosition = 2; n = n & ~ (1 << [1]); console.log(n.toString(2));
Attempts:
3 left
💡 Hint
Common Mistakes
Using 2 instead of 1 for bit position
Forgetting to invert the mask
✗ Incorrect
To clear the 2nd bit, shift 1 left by 1 (zero-based), then invert and AND.
3fill in blank
hardFix the error in toggling the 1st bit of number n.
DSA Javascript
let n = 5; // 0101 in binary let bitPosition = 0; n = n [1] (1 << bitPosition); console.log(n.toString(2));
Attempts:
3 left
💡 Hint
Common Mistakes
Using OR instead of XOR
Using AND which clears bits
✗ Incorrect
Toggling a bit uses XOR (^), which flips the bit at the position.
4fill in blank
hardFill both blanks to set and then clear the 4th bit of number n.
DSA Javascript
let n = 10; // 1010 in binary let bitPosition = 3; n = n [1] (1 << bitPosition); n = n [2] ~ (1 << bitPosition); console.log(n.toString(2));
Attempts:
3 left
💡 Hint
Common Mistakes
Using XOR to set or clear bits
Forgetting to invert mask when clearing
✗ Incorrect
Use OR to set a bit and AND with NOT to clear it.
5fill in blank
hardFill all three blanks to toggle the 0th bit, set the 2nd bit, and clear the 3rd bit of number n.
DSA Javascript
let n = 13; // 1101 in binary n = n [1] (1 << 0); n = n [2] (1 << 1); n = n [3] ~ (1 << 2); console.log(n.toString(2));
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up operators for set/clear/toggle
Forgetting to invert mask when clearing
✗ Incorrect
Toggling uses XOR (^), setting uses OR (|), clearing uses AND (&) with NOT.
