bit manipulation
programming techniques
boolean algebra
binary operations
software development

Most elegant way to change 0 to 1 and vice versa

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If a variable is guaranteed to hold only 0 or 1, flipping it is a tiny operation with a surprisingly common role in real code. You see it in bit manipulation, state machines, parity checks, and compact flag handling. The most elegant answer depends on whether the value is an integer bit or a language-level boolean, but for a numeric 0 or 1, XOR with 1 is the clearest low-level solution.

The Bitwise XOR Solution

XOR toggles a bit because a bit changes only when it is XORed with 1. That gives a concise rule:

  • '0 ^ 1 becomes 1'
  • '1 ^ 1 becomes 0'

In C, C++, Java, JavaScript, and many other languages, this is a single simple expression:

c
1#include <stdio.h>
2
3int main(void) {
4    int bit = 0;
5    bit ^= 1;
6    printf("%d\n", bit);
7
8    bit ^= 1;
9    printf("%d\n", bit);
10    return 0;
11}

Output:

text
1
0

This is usually the best answer when you are explicitly working with bits. It communicates that the value is binary state, not just any integer.

Arithmetic Alternatives

If you want a language-agnostic mathematical expression, 1 - x also works when x is guaranteed to be either 0 or 1.

python
1def flip_bit(x: int) -> int:
2    if x not in (0, 1):
3        raise ValueError("x must be 0 or 1")
4    return 1 - x
5
6
7print(flip_bit(0))
8print(flip_bit(1))

This prints:

python
1
0

The arithmetic form is readable, but it is less explicit about bit intent. If you are writing systems code or explaining bit toggling, XOR is usually stronger.

Booleans Are A Separate Case

Many languages have a real boolean type, and in that case you should normally toggle the boolean instead of converting it to integers. That keeps the code aligned with the type system.

For example, in Python:

python
1flag = False
2flag = not flag
3print(flag)
4
5flag = not flag
6print(flag)

And in JavaScript:

javascript
1let enabled = false;
2enabled = !enabled;
3console.log(enabled);
4
5enabled = !enabled;
6console.log(enabled);

That is more idiomatic than forcing booleans through numeric expressions. If the variable represents truth, use boolean operators. If it represents a bit, use bit operations.

Toggling A Bit Inside A Larger Integer

Sometimes you are not flipping a standalone variable. You are flipping one bit inside a mask. XOR is still the right tool:

python
1mask = 0b1010
2bit_index = 1
3
4mask ^= 1 << bit_index
5print(bin(mask))

This changes only the target bit. That is one reason XOR is so common in low-level code: the same mental model scales from a single 0 or 1 to a full bitset.

Common Pitfalls

The main pitfall is assuming the value is binary when it is not. x ^= 1 does not mean "swap any number between zero and one." If x is 2, the result is 3, which is probably not what you want.

Another mistake is using integer tricks for boolean variables in languages with a clear boolean type. That makes the code harder to read and can introduce subtle bugs if the variable later stops being strictly numeric.

Be careful with user input as well. Strings like "0" and "1" need parsing before you can toggle them correctly. Otherwise you may end up applying operators to the wrong type.

Finally, do not over-optimize. Compilers understand these patterns very well. Choose the expression that best matches the meaning of the variable.

Summary

  • For an integer known to be 0 or 1, x ^= 1 is the most direct bitwise toggle.
  • '1 - x works too, but it emphasizes arithmetic rather than bit manipulation.'
  • For booleans, prefer not or ! instead of numeric tricks.
  • XOR also scales naturally to toggling one bit inside a larger mask.
  • Validate assumptions if the input may contain values other than 0 or 1.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.