4. The following TypeScript code is intended to toggle the bit at position pos in num. What is the error?
let num = 5; // binary 0101
let pos = 2;
num = num & (1 << pos);
console.log(num);
medium
A. It only keeps the bit at pos and clears others
B. It clears the bit instead of toggling
C. It sets the bit instead of toggling
D. It causes a syntax error
Solution
Step 1: Analyze the operation used
The code uses num & (1 << pos), which ANDs num with a mask having 1 only at pos.
Step 2: Understand effect of AND with mask
This operation keeps only the bit at pos and clears all other bits, not toggling the bit.
Final Answer:
It only keeps the bit at pos and clears others -> Option A
Quick Check:
AND with mask keeps only that bit [OK]
Hint: AND with mask keeps only that bit, doesn't toggle [OK]
Common Mistakes:
Confusing AND with XOR for toggling
Expecting toggle but using AND
Ignoring effect on other bits
5. You have a number num = 29 (binary 11101). You want to toggle the bits at positions 0, 2, and 4 simultaneously. Which TypeScript code correctly does this?
hard
A. num = num | ((1 << 0) & (1 << 2) & (1 << 4));
B. num = num & ~((1 << 0) | (1 << 2) | (1 << 4));
C. num = num ^ ((1 << 0) | (1 << 2) | (1 << 4));
D. num = num ^ (1 << 0) & (1 << 2) & (1 << 4);
Solution
Step 1: Create mask for bits 0, 2, and 4
Using OR to combine shifted bits: (1 << 0) | (1 << 2) | (1 << 4) creates mask 10101 binary (decimal 21).
Step 2: Use XOR to toggle bits
XOR with this mask toggles bits 0, 2, and 4 in num.
Final Answer:
num = num ^ ((1 << 0) | (1 << 2) | (1 << 4)); -> Option C
Quick Check:
XOR with combined mask toggles multiple bits [OK]
Hint: Combine bits with OR, toggle with XOR [OK]
Common Mistakes:
Using AND or OR instead of XOR to toggle
Using AND between shifted bits instead of OR
Not combining bits before toggling
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.