Bird
Raised Fist0
DSA Javascriptprogramming

Set Clear Toggle a Specific Bit in DSA Javascript

Choose your learning style10 modes available
Mental Model
We change one specific light switch in a row without touching the others by turning it on, off, or flipping it.
Analogy: Imagine a row of light switches representing bits. Setting a bit is like turning a switch ON, clearing a bit is turning it OFF, and toggling is flipping the switch from ON to OFF or OFF to ON.
Bits: 0 1 0 1 1 0 0 1
Index: 7 6 5 4 3 2 1 0
          ↑
       target bit
Dry Run Walkthrough
Input: number = 0b01011001 (89 decimal), bit position = 3
Goal: Set, clear, and toggle the bit at position 3 (counting from 0 at right) in the number
Step 1: Set bit 3 to 1 using OR with mask
Original: 0 1 0 1 1 0 0 1 (0b01011001)
Mask:     0 0 0 0 1 0 0 0 (0b00001000)
Result:   0 1 0 1 1 0 0 1 (0b01011001)
Why: Bit 3 is already 1, so setting keeps it ON
Step 2: Clear bit 3 to 0 using AND with inverted mask
Original: 0 1 0 1 1 0 0 1 (0b01011001)
Mask:     1 1 1 1 0 1 1 1 (0b11110111)
Result:   0 1 0 1 0 0 0 1 (0b01010001)
Why: AND with mask clears bit 3 to 0, others stay same
Step 3: Toggle bit 3 using XOR with mask
Original: 0 1 0 1 0 0 0 1 (0b01010001)
Mask:     0 0 0 0 1 0 0 0 (0b00001000)
Result:   0 1 0 1 1 0 0 1 (0b01011001)
Why: XOR flips bit 3 from 0 to 1
Step 4: Toggle bit 3 again using XOR with mask
Original: 0 1 0 1 1 0 0 1 (0b01011001)
Mask:     0 0 0 0 1 0 0 0 (0b00001000)
Result:   0 1 0 1 0 0 0 1 (0b01010001)
Why: XOR flips bit 3 back from 1 to 0
Result:
Final bits after toggle twice: 0 1 0 1 0 0 0 1 (0b01010001)
Annotated Code
DSA Javascript
class BitManipulator {
  constructor(number) {
    this.number = number;
  }

  setBit(pos) {
    // Create mask with 1 at pos
    const mask = 1 << pos;
    // OR sets bit at pos
    this.number = this.number | mask;
  }

  clearBit(pos) {
    // Create mask with 1 at pos
    const mask = 1 << pos;
    // AND with inverted mask clears bit at pos
    this.number = this.number & ~mask;
  }

  toggleBit(pos) {
    // Create mask with 1 at pos
    const mask = 1 << pos;
    // XOR flips bit at pos
    this.number = this.number ^ mask;
  }

  toBinaryString() {
    return this.number.toString(2).padStart(8, '0');
  }
}

// Driver code
const bm = new BitManipulator(0b01011001); // 89 decimal
const pos = 3;

console.log('Original:', bm.toBinaryString());

bm.setBit(pos);
console.log('After setBit:', bm.toBinaryString());

bm.clearBit(pos);
console.log('After clearBit:', bm.toBinaryString());

bm.toggleBit(pos);
console.log('After toggleBit:', bm.toBinaryString());

bm.toggleBit(pos);
console.log('After toggleBit again:', bm.toBinaryString());
const mask = 1 << pos;
Create mask with 1 at target bit position
this.number = this.number | mask;
Set bit by OR operation
this.number = this.number & ~mask;
Clear bit by AND with inverted mask
this.number = this.number ^ mask;
Toggle bit by XOR operation
OutputSuccess
Original: 01011001 After setBit: 01011001 After clearBit: 01010001 After toggleBit: 01011001 After toggleBit again: 01010001
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of number size
Space: O(1) because no extra space is needed beyond fixed variables
vs Alternative: Compared to looping through bits or converting to string, bitwise operations are much faster and use less memory
Edge Cases
bit position outside 0-31 range
Bit shift may produce unexpected results or zero mask; code assumes valid position
DSA Javascript
const mask = 1 << pos;
number is zero
Setting bit turns that bit ON; clearing bit keeps zero; toggling flips bit correctly
DSA Javascript
this.number = this.number | mask;
bit already set when setting
Number remains unchanged, no error
DSA Javascript
this.number = this.number | mask;
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.
Common Mistakes
Mistake: Using left shift with negative or too large bit positions causing wrong masks
Fix: Ensure bit position is within valid range (0 to 31) before shifting
Mistake: Using OR to clear bits or AND to set bits incorrectly
Fix: Use OR to set bits, AND with inverted mask to clear bits, XOR to toggle bits
Summary
It changes one specific bit in a number by setting it to 1, clearing it to 0, or flipping it.
Use it when you want to control individual bits efficiently in numbers.
The key is to create a mask with a 1 at the target bit and use OR, AND, or XOR to change that bit.

Practice

(1/5)
1. What does the operation num | (1 << k) do to the number num in terms of bits?
easy
A. Toggles the k-th bit of num
B. Sets the k-th bit of num to 1
C. Clears the k-th bit of num to 0
D. Checks if the k-th bit of num is set

Solution

  1. Step 1: Understand bitwise OR with shifted 1

    The expression 1 << k creates a number with only the k-th bit set to 1.
  2. Step 2: Apply OR operation to set bit

    Using num | (1 << k) sets the k-th bit of num to 1 without changing other bits.
  3. Final Answer:

    Sets the k-th bit of num to 1 -> Option B
  4. Quick Check:

    Bitwise OR with 1 at position k sets that bit [OK]
Hint: Use OR with shifted 1 to set a bit [OK]
Common Mistakes:
  • Confusing set with clear operation
  • Thinking it toggles the bit
  • Assuming it checks the bit instead
2. Which of the following JavaScript expressions correctly clears the k-th bit of a number num?
easy
A. num ^ (1 << k)
B. num | ~(1 << k)
C. num & (1 << k)
D. num & ~(1 << k)

Solution

  1. Step 1: Understand clearing a bit

    To clear the k-th bit, we want to set it to 0 while keeping others unchanged.
  2. Step 2: Use AND with NOT mask

    The mask ~(1 << k) has all bits 1 except the k-th bit 0. ANDing with this clears the k-th bit.
  3. Final Answer:

    num & ~(1 << k) -> Option D
  4. Quick Check:

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

Solution

  1. Step 1: Understand initial values and bit positions

    num = 10 (binary 1010), k = 1 means second bit from right (0-based).
  2. Step 2: Apply XOR to toggle k-th bit

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

    8 -> Option A
  4. Quick Check:

    XOR toggles bit 1: 10 -> 8 [OK]
Hint: XOR toggles the bit at position k [OK]
Common Mistakes:
  • Confusing XOR with OR or AND
  • Miscounting bit positions (0-based)
  • Not converting binary to decimal correctly
4. The following code is intended to toggle the k-th bit of num. What is the error?
function toggleBit(num, k) {
  return num & (1 << k);
}
console.log(toggleBit(5, 0));
medium
A. Function does not return a number
B. Incorrect bit shift direction
C. Using AND instead of XOR to toggle the bit
D. Missing parentheses around bit shift

Solution

  1. Step 1: Identify intended toggle operation

    Toggling a bit requires flipping it: 0 to 1 or 1 to 0.
  2. Step 2: Check the operator used

    The code uses AND (&) which masks bits, not toggles. XOR (^) is needed to toggle bits.
  3. Final Answer:

    Using AND instead of XOR to toggle the bit -> Option C
  4. Quick Check:

    Toggle needs XOR, not AND [OK]
Hint: Toggle bits with XOR, not AND [OK]
Common Mistakes:
  • Using AND or OR instead of XOR for toggle
  • Confusing toggle with set or clear
  • Ignoring operator precedence
5. You want to write a function updateBit(num, k, bitValue) that sets the k-th bit of num to bitValue (0 or 1). Which of the following implementations is correct?
hard
A. return (num & ~(1 << k)) | (bitValue << k);
B. return (num | (bitValue << k)) & ~(bitValue << k);
C. return num ^ (bitValue << k);
D. return num & (bitValue << k);

Solution

  1. Step 1: Clear the k-th bit first

    Use num & ~(1 << k) to clear the k-th bit regardless of its current value.
  2. Step 2: Set the k-th bit to bitValue

    Shift bitValue to k-th position and OR it with cleared number to set the bit correctly.
  3. Final Answer:

    return (num & ~(1 << k)) | (bitValue << k); -> Option A
  4. Quick Check:

    Clear then set bit with OR [OK]
Hint: Clear bit then OR with shifted bitValue to update [OK]
Common Mistakes:
  • Using XOR which toggles instead of sets
  • Not clearing bit before setting
  • Using AND which masks bits incorrectly
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