Bird
Raised Fist0
DSA Typescriptprogramming

Set Clear Toggle a Specific Bit in DSA Typescript

Choose your learning style10 modes available
Mental Model
We change one specific bit in a number to 1, 0, or flip it without affecting other bits.
Analogy: Imagine a row of light switches where each switch controls one light. Setting a bit is like turning a switch on, clearing is turning it off, and toggling is flipping its current state.
Bits:  7 6 5 4 3 2 1 0
Value: 0 0 1 0 1 0 0 1
Index:          ↑
Operation: change bit at index 3
Dry Run Walkthrough
Input: number = 41 (binary 00101001), index = 3
Goal: Set bit 3 to 1, clear bit 3 to 0, and toggle bit 3
Step 1: Set bit 3 to 1 using OR with mask
00101001 (41) -> mask 00001000 (bit 3)
Result: 00101001 | 00001000 = 00101001 (41)
Why: Bit 3 is already 1, so setting it keeps the number same
Step 2: Clear bit 3 to 0 using AND with inverted mask
00101001 (41) -> mask 11110111 (inverted bit 3)
Result: 00101001 & 11110111 = 00100001 (33)
Why: Clearing bit 3 changes it from 1 to 0
Step 3: Toggle bit 3 using XOR with mask
00100001 (33) -> mask 00001000 (bit 3)
Result: 00100001 ^ 00001000 = 00101001 (41)
Why: Toggling flips bit 3 back to 1
Result:
Final values:
Set bit 3: 41 (00101001)
Clear bit 3: 33 (00100001)
Toggle bit 3: 41 (00101001)
Annotated Code
DSA Typescript
class BitManipulator {
  static setBit(num: number, index: number): number {
    return num | (1 << index); // set bit to 1
  }

  static clearBit(num: number, index: number): number {
    return num & ~(1 << index); // clear bit to 0
  }

  static toggleBit(num: number, index: number): number {
    return num ^ (1 << index); // flip bit
  }
}

// Driver code
const num = 41; // binary 00101001
const index = 3;

const setResult = BitManipulator.setBit(num, index);
const clearResult = BitManipulator.clearBit(num, index);
const toggleResult = BitManipulator.toggleBit(clearResult, index);

console.log(`Set bit ${index}: ${setResult} (${setResult.toString(2).padStart(8, '0')})`);
console.log(`Clear bit ${index}: ${clearResult} (${clearResult.toString(2).padStart(8, '0')})`);
console.log(`Toggle bit ${index}: ${toggleResult} (${toggleResult.toString(2).padStart(8, '0')})`);
return num | (1 << index);
set bit at index to 1 by OR with mask
return num & ~(1 << index);
clear bit at index to 0 by AND with inverted mask
return num ^ (1 << index);
toggle bit at index by XOR with mask
OutputSuccess
Set bit 3: 41 (00101001) Clear bit 3: 33 (00100001) Toggle bit 3: 41 (00101001)
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of input size
Space: O(1) because no extra space is used except a few variables
vs Alternative: Using arithmetic or string conversion to manipulate bits is slower and more complex compared to direct bitwise operations
Edge Cases
index is 0 (least significant bit)
Operations correctly affect the rightmost bit
DSA Typescript
return num | (1 << index);
index is out of range (negative or >= number of bits)
Bit shift results in zero or undefined behavior; code assumes valid index
DSA Typescript
No explicit guard; user must provide valid index
number is 0
Setting bit sets that bit to 1; clearing bit keeps 0; toggling flips bit
DSA Typescript
return num | (1 << index);
When to Use This Pattern
When you need to change a single bit in a number without affecting others, use set, clear, or toggle bit patterns with bitwise operators for efficient manipulation.
Common Mistakes
Mistake: Using AND instead of OR to set a bit, which can clear bits instead
Fix: Use OR with mask to set a bit: num | (1 << index)
Mistake: Not inverting the mask when clearing a bit, causing wrong bits to be cleared
Fix: Use AND with inverted mask: num & ~(1 << index)
Mistake: Using OR or AND instead of XOR to toggle a bit, which won't flip the bit correctly
Fix: Use XOR with mask: num ^ (1 << index)
Summary
It changes one specific bit in a number to 1, 0, or flips it.
Use it when you want to manipulate individual bits efficiently.
The key is using bitwise OR to set, AND with inverted mask to clear, and XOR to toggle bits.

Practice

(1/5)
1. What does the operation num | (1 << pos) do to the bit at position pos in the number num?
easy
A. Toggles the bit at position pos
B. Clears the bit at position pos to 0
C. Checks if the bit at position pos is 1
D. Sets the bit at position pos to 1

Solution

  1. Step 1: Understand bitwise OR with shifted 1

    The expression 1 << pos creates a number with only the bit at position pos set to 1.
  2. Step 2: Apply OR operation to set bit

    Using num | (1 << pos) sets the bit at pos to 1 without changing other bits.
  3. Final Answer:

    Sets the bit at position pos to 1 -> Option D
  4. Quick Check:

    Bitwise OR with 1 at pos sets bit [OK]
Hint: Use OR with shifted 1 to set a bit [OK]
Common Mistakes:
  • Confusing set with clear operation
  • Using AND instead of OR to set bit
  • Thinking it toggles the bit
2. Which of the following TypeScript code snippets correctly clears (sets to 0) the bit at position pos in the variable num?
easy
A. num = num & (1 << pos);
B. num = num & ~(1 << pos);
C. num = num | (1 << pos);
D. num = num ^ (1 << pos);

Solution

  1. Step 1: Understand clearing a bit

    To clear a bit, we AND the number with a mask that has 0 at the target bit and 1s elsewhere.
  2. Step 2: Create mask with NOT operator

    ~(1 << pos) creates a mask with 0 at pos and 1s elsewhere, so num & ~(1 << pos) clears the bit.
  3. Final Answer:

    num = num & ~(1 << pos); -> Option B
  4. Quick Check:

    AND with NOT mask clears bit [OK]
Hint: Use AND with NOT shifted 1 to clear bit [OK]
Common Mistakes:
  • Using OR instead of AND to clear bit
  • Forgetting to negate the mask
  • Using XOR which toggles instead of clears
3. What is the output of the following TypeScript code?
let num = 10; // binary 1010
let pos = 1;
num = num ^ (1 << pos);
console.log(num);
medium
A. 8
B. 10
C. 12
D. 14

Solution

  1. Step 1: Understand initial values and bit positions

    Number 10 in binary is 1010. Bit positions (0-based) from right: pos 0=0, pos 1=1, pos 2=0, pos 3=1.
  2. Step 2: Apply XOR to toggle bit at position 1

    1 << 1 is 2 (binary 0010). XOR toggles bit 1: 1010 ^ 0010 = 1000 (binary), which is 8 decimal.
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    Toggle bit 1 in 10 gives 8 [OK]
Hint: XOR toggles bit; toggle 1 in 1010 gives 1000 (8) [OK]
Common Mistakes:
  • Confusing XOR with OR or AND
  • Miscounting bit positions
  • Assuming toggle sets bit always to 1
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

  1. Step 1: Analyze the operation used

    The code uses num & (1 << pos), which ANDs num with a mask having 1 only at pos.
  2. 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.
  3. Final Answer:

    It only keeps the bit at pos and clears others -> Option A
  4. 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

  1. 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).
  2. Step 2: Use XOR to toggle bits

    XOR with this mask toggles bits 0, 2, and 4 in num.
  3. Final Answer:

    num = num ^ ((1 << 0) | (1 << 2) | (1 << 4)); -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard