Bird
Raised Fist0
DSA Javaprogramming

Set Clear Toggle a Specific Bit in DSA Java

Choose your learning style10 modes available
Mental Model
We can change a single bit in a number by using simple math tricks without touching other bits.
Analogy: Imagine a row of light switches where each switch controls one light bulb. You can turn one bulb on, off, or flip its state without changing the others.
Number bits: 0 0 1 0 1 1 0 1
Bit positions: 7 6 5 4 3 2 1 0
Toggle bit 3 (counting from 0 at right)
Dry Run Walkthrough
Input: number = 45 (binary 00101101), toggle bit at position 3
Goal: Flip the bit at position 3 from 1 to 0 or 0 to 1 without changing other bits
Step 1: Create mask by shifting 1 left by 3 positions
mask = 00001000 (binary), number = 00101101
Why: Mask isolates the bit at position 3 to toggle it
Step 2: Apply XOR between number and mask to toggle bit
result = 00101101 XOR 00001000 = 00100101
Why: XOR flips the bit at position 3, leaves others unchanged
Step 3: Convert result to decimal
result = 37 (decimal), binary 00100101
Why: Final number after toggling bit 3
Result:
00100101 (binary) -> 37 (decimal)
Annotated Code
DSA Java
public class BitManipulation {
    // Toggle bit at given position (0-based from right)
    public static int toggleBit(int number, int position) {
        int mask = 1 << position; // create mask with 1 at position
        return number ^ mask; // XOR toggles the bit
    }

    public static void main(String[] args) {
        int number = 45; // binary 00101101
        int position = 3;
        int result = toggleBit(number, position);
        System.out.println("Original number: " + number + " (binary " + String.format("%8s", Integer.toBinaryString(number)).replace(' ', '0') + ")");
        System.out.println("Toggle bit at position " + position);
        System.out.println("Result number: " + result + " (binary " + String.format("%8s", Integer.toBinaryString(result)).replace(' ', '0') + ")");
    }
}
int mask = 1 << position; // create mask with 1 at position
create mask to isolate the bit to toggle
return number ^ mask; // XOR toggles the bit
toggle the bit using XOR operation
OutputSuccess
Original number: 45 (binary 00101101) Toggle bit at position 3 Result number: 37 (binary 00100101)
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of number size
Space: O(1) because only a few variables are used for mask and result
vs Alternative: Compared to converting number to binary string and manipulating characters, bitwise operations are much faster and use less memory
Edge Cases
position is 0 (toggle least significant bit)
correctly toggles the rightmost bit
DSA Java
int mask = 1 << position;
position is 31 (for 32-bit int)
still works correctly because shift operator handles it, toggling that bit
DSA Java
int mask = 1 << position;
number is 0 (all bits off)
toggles the bit from 0 to 1 at position
DSA Java
return number ^ mask;
When to Use This Pattern
When you need to change exactly one bit in a number without affecting others, use bitwise operations like XOR to toggle, OR to set, and AND with NOT to clear bits.
Common Mistakes
Mistake: Using OR instead of XOR to toggle bit, which only sets bit to 1 and never clears it
Fix: Use XOR (^) operator to flip the bit instead of OR (|)
Mistake: Shifting 1 by position without checking if position is valid, causing unexpected results
Fix: Ensure position is within valid range (0 to 31 for int) before shifting
Summary
It changes a single bit in a number by flipping it from 0 to 1 or 1 to 0.
Use it when you want to toggle a specific bit without changing other bits in a number.
The key is to create a mask with 1 at the target bit and XOR it with the number to flip that bit.

Practice

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

Solution

  1. Step 1: Understand the bit shift operation

    1 << k creates a number with only the k-th bit set to 1 and all others 0.
  2. Step 2: Apply bitwise OR with num

    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 C
  4. Quick Check:

    Set bit = OR with 1 shifted [OK]
Hint: Use OR with 1 shifted to set a bit [OK]
Common Mistakes:
  • Confusing OR with AND operation
  • Thinking it clears or toggles the bit
  • Misunderstanding bit positions starting at 0
2. Which of the following Java statements correctly clears (sets to 0) the 3rd bit (0-based) of an integer variable num?
easy
A. num = num & (1 << 3);
B. num = num & ~(1 << 3);
C. num = num ^ (1 << 3);
D. num = num | (1 << 3);

Solution

  1. Step 1: Understand clearing a bit

    To clear a bit, we AND with a mask that has 0 at that bit and 1s elsewhere.
  2. Step 2: Create mask and apply

    ~(1 << 3) creates a mask with all 1s except 0 at bit 3. ANDing num with this clears bit 3.
  3. Final Answer:

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

    Clear bit = AND with NOT mask [OK]
Hint: Clear bit by AND with NOT of shifted 1 [OK]
Common Mistakes:
  • Using OR instead of AND to clear bits
  • Using XOR which toggles bits
  • Using AND with shifted 1 which keeps only that bit
3. What is the output of the following Java code?
int num = 10; // binary 1010
int k = 1;
num = num ^ (1 << k);
System.out.println(num);
medium
A. 10
B. 14
C. 12
D. 8

Solution

  1. Step 1: Understand initial value and bit positions

    num = 10 in binary is 1010. Bit positions (0-based) from right: bit0=0, bit1=1, bit2=0, bit3=1.
  2. Step 2: Apply XOR to toggle bit 1

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

    8 -> Option D
  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
  • Misreading bit positions starting at 1 instead of 0
  • Incorrect binary to decimal conversion
4. The following Java code is intended to toggle the 2nd bit of num. What is the error?
int num = 5; // binary 0101
int k = 2;
num = num & (1 << k);
System.out.println(num);
medium
A. It clears all bits except the 2nd bit instead of toggling
B. It toggles the wrong bit
C. It causes a syntax error
D. It sets the 2nd bit to 1 always

Solution

  1. Step 1: Analyze the operation used

    The code uses AND with 1 << k, which keeps only the k-th bit and clears others.
  2. Step 2: Understand toggle operation

    Toggle requires XOR, not AND. AND here does not toggle but masks all bits except bit 2.
  3. Final Answer:

    It clears all bits except the 2nd bit instead of toggling -> Option A
  4. Quick Check:

    Toggle = XOR, not AND mask [OK]
Hint: Toggle bits using XOR, not AND [OK]
Common Mistakes:
  • Using AND instead of XOR to toggle bits
  • Confusing bit positions
  • Expecting output without understanding bitwise operations
5. Given an integer num, write a Java expression to toggle the 0th bit only if it is currently set (1), otherwise leave num unchanged. Which expression achieves this?
hard
A. num = (num & (1 << 0)) != 0 ? num ^ (1 << 0) : num;
B. num = num & ~(1 << 0);
C. num = num ^ (1 << 0);
D. num = num | (1 << 0);

Solution

  1. Step 1: Check if 0th bit is set

    Use (num & (1 << 0)) != 0 to test if bit 0 is 1.
  2. Step 2: Toggle bit 0 only if set

    If bit 0 is set, toggle it with XOR; else keep num unchanged.
  3. Final Answer:

    num = (num & (1 << 0)) != 0 ? num ^ (1 << 0) : num; -> Option A
  4. Quick Check:

    Conditional toggle only if bit set [OK]
Hint: Use conditional check before toggling bit [OK]
Common Mistakes:
  • Toggling bit unconditionally
  • Using OR which always sets bit
  • Clearing bit without condition
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