Understand
30-second explanation
Build the interview-ready mental model before comparing implementations.
Flip every one of the 32 bits of an unsigned integer. XOR with a 32-bit all-ones mask: n ^ 0xFFFFFFFF turns every 0 into 1 and every 1 into 0. Equivalently it equals 4294967295 − n, since flipping all bits of a value below the all-ones ceiling is just subtracting it from that ceiling. It is O(1) — no loop.
Interview contextWhat is testedWhere candidates slipHow to stand outExplore interview contextHide interview context
What's being tested
Whether you know XOR with 1 toggles a bit and can build a 32-bit all-ones mask, plus the language gotchas: masking ~n in Python and using an unsigned-safe type in Java.
Where candidates slip
Returning bare ~n in Python (a negative, infinitely-wide number) without the & 0xFFFFFFFF mask, or using a 32-bit signed int in Java so the high bit makes the result negative.
How to stand out
Give the one-line XOR-with-mask answer, mention the 4294967295 − n equivalence and why it holds, and call out the masking/typing requirement for the language you're in.
Choose
Compare the available approaches
Use constraints and trade-offs to select the route you can defend in an interview.
Interactive decision treeInteractiveChoose the right approachFirst decision previewFlip all 32 bits of unsigned nLoop each bit?YesNoExplore the full treeCollapse the tree
Learn & trace
Build each solution step by step
Move from the core idea to a visual trace, implementation, proof, and edge cases.
Approach 1 of 2
Bit-by-Bit Loop — Toggle Each Position
1Hint 1Explore hintHide hint
Walk the 32 bit positions. For each position i, read bit (n >> i) & 1.
2Hint 2Explore hintHide hint
If that bit is 0, set the corresponding bit in the result; if it's 1, leave the result's bit as 0.
3Hint 3Explore hintHide hint
After 32 iterations the result holds the flipped value. It's constant time (32 is fixed) but verbose.
A · Core idea
Invert the number one position at a time to make the mechanics explicit.
The per-bit logic. For each of the 32 positions, extract the bit with (n >> i) & 1. Flipping means: a 0 should become a 1, and a 1 should become a 0. So whenever the extracted bit is 0, set bit i in the result with result |= (1L << i); whenever it is 1, do nothing (the result bit is already 0).
Why 32 positions exactly. The value is an unsigned 32-bit integer, so there are precisely 32 bits to consider — including the leading zeros of a small number, which must flip to ones. Looping i from 0 to 31 covers them all.
Why this is correct but clunky. It produces the right answer and runs in constant time (32 is a fixed bound), but it spells out by hand what a single XOR does atomically. Every one of those 32 conditional sets is just 'toggle this bit', which is exactly XOR with 1. Recognising that lets you replace the entire loop with one masked operation.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 1 (binary ...0001)Interactive diagram
Toggling positions one at a time
i=0Each bit is inspected and flipped — the loop unrolls the single XOR below.
4294967294C · Code with teaching comments
Reference implementation previewpublic long flippingBits(long n) { long result = 0; for (int i = 0; i < 32; i++) { long bit = (n >> i) & 1; // read bit i if (bit == 0) {Explore the full codeHide the full code
D · Why it works and complexityO(1) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
Each loop step is 'flip bit i' — and flipping a bit is XOR with 1. Thirty-two such flips at once is XOR with thirty-two 1s, i.e. 0xFFFFFFFF. The loop is the unrolled form of the optimal one-liner.
ComplexityO(1) time, O(1) space — Exactly 32 iterations regardless of n, each doing constant bit work — O(1) time and O(1) space, just with a large constant factor.
E · Edge cases and pitfalls3Looping only 31 times or up to the highest set bit — leading zeros must flip too.Explore edge casesHide edge cases
Pitfalls
- Looping only 31 times or up to the highest set bit — leading zeros must flip too.
- Using (1 << i) on a 32-bit int in Java and overflowing the sign bit — use 1L << i.
- Writing the loop at all when one XOR does the whole job.
Approach 2 of 2 · Optimal
XOR with All-Ones Mask (Optimal)
1Hint 1Explore hintHide hint
XOR with 1 flips a bit; XOR with 0 leaves it. To flip all 32 bits, XOR against 32 ones.
2Hint 2Explore hintHide hint
Thirty-two ones is the constant 0xFFFFFFFF = 4294967295. So the answer is n ^ 0xFFFFFFFF.
3Hint 3Explore hintHide hint
Mind the language: in Python mask with & 0xFFFFFFFF if you use ~n; in Java use a long literal 0xFFFFFFFFL.
A · Core idea
Replace the 32-step loop with one masked operation.
Why XOR with all ones flips everything. XOR is the 'toggle if the mask bit is 1' operator: b ^ 1 is the opposite of b, and b ^ 0 is b unchanged. A mask of all ones therefore toggles every bit simultaneously. For 32 bits the all-ones mask is 0xFFFFFFFF, so n ^ 0xFFFFFFFF is the full bitwise inversion in one shot.
The subtraction equivalence. Because 0xFFFFFFFF is all ones, subtracting any 32-bit n from it never triggers a borrow — at every position you compute 1 − bit, which is exactly the complement of that bit. So 4294967295 − n produces the identical result. Either form is fine; the XOR makes the intent (flip bits) clearer.
The Python gotcha. Python integers are arbitrary precision, so the built-in ~n returns −(n + 1) — a negative number with infinitely many leading ones, not a 32-bit value. To get the unsigned 32-bit complement you must mask: ~n & 0xFFFFFFFF, or just use n ^ 0xFFFFFFFF which is already bounded.
The Java gotcha. A 32-bit signed int would interpret a flipped result with its top bit set as negative. Use a long and the literal 0xFFFFFFFFL so the value stays in the unsigned 32-bit range [0, 4294967295].
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 0Interactive diagram
One XOR flips all 32 bits
maskThe mask is 32 ones; XOR toggles each position at once.
4294967295C · Code with teaching comments
D · Why it works and complexityO(1) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
Flipping a fixed-width number is one XOR with an all-ones mask of that width — and that equals subtracting it from the all-ones ceiling. The only real work is getting the width and the language's integer semantics right.
ComplexityO(1) time, O(1) space — A single XOR (or subtraction) — one machine operation, no loop, no allocation. O(1) time and space.
E · Edge cases and pitfalls6n = 0 — 0 ^ 0xFFFFFFFF = 4294967295 — all zeros flip to all ones.Explore edge casesHide edge cases
Edge cases handled
n = 00 ^ 0xFFFFFFFF = 4294967295 — all zeros flip to all ones.n = 42949672950xFFFFFFFF ^ 0xFFFFFFFF = 0 — all ones flip to all zeros.n = 21474836480x80000000 ^ 0xFFFFFFFF = 0x7FFFFFFF = 2147483647 — only the top bit was set, now cleared.
Pitfalls
- Returning bare ~n in Python — gives a negative, infinite-width number instead of the 32-bit complement.
- Using a signed 32-bit int in Java so the flipped value reads as negative — use long with 0xFFFFFFFFL.
- Masking with the wrong width (0xFFFF or 0xFFFFFFFFFFFFFFFF) and flipping too few or too many bits.
Practice
Try the solution yourself
Edit the optimal implementation, test another input, and observe the result.
Editable code previewpublic long flippingBits(long n) { return n ^ 0xFFFFFFFFL; // flip all 32 bits; long keeps it unsigned-safe }Explore the playgroundClose the playground
Avoid mistakes
Recognize the interview traps
Understand why common attempts fail before reviewing the corrected implementation.
1Unmasked complement in Python
Python ints are arbitrary precision, so ~n = −(n+1) with infinite leading ones — not a 32-bit unsigned value.
Explore the code comparisonHide the code comparison
Unmasked complement in Python
Python ints are arbitrary precision, so ~n = −(n+1) with infinite leading ones — not a 32-bit unsigned value.
Don't write this
return ~n # negative, infinite-widthWrite this instead
return ~n & 0xFFFFFFFF # bounded to 32 bits2Signed int in Java
A 32-bit int treats a result with the high bit set as negative. Use a long and the L-suffixed mask.
Explore the code comparisonHide the code comparison
Signed int in Java
A 32-bit int treats a result with the high bit set as negative. Use a long and the L-suffixed mask.
Don't write this
int result = (int) n ^ 0xFFFFFFFF; // can be negativeWrite this instead
long result = n ^ 0xFFFFFFFFL; // unsigned-safe3Wrong mask width
Flipping 32 bits needs exactly 32 ones. A 16-bit or 64-bit mask flips the wrong number of positions.
Explore the code comparisonHide the code comparison
Wrong mask width
Flipping 32 bits needs exactly 32 ones. A 16-bit or 64-bit mask flips the wrong number of positions.
Don't write this
return n ^ 0xFFFF # only 16 bits flippedWrite this instead
return n ^ 0xFFFFFFFF # all 32 bits flippedRevise
Carry the pattern into the interview
Pattern to remember
XOR with a 32-bit all-ones mask
Code pattern to memorize
return n ^ 0xFFFFFFFF # flip the low 32 bits
# equivalently: 4294967295 - n
# equivalently: ~n & 0xFFFFFFFFRules to remember
- 1XOR with 1 flips a bit; XOR with 0 leaves it. A mask of all 1s (0xFFFFFFFF) flips every one of the 32 bits at once.
- 2The mask is exactly 32 ones =
0xFFFFFFFF=4294967295. Use this width — not 31, not 64. - 34294967295 − n gives the same answer because no borrow ever happens: all-ones minus any 32-bit value is its bitwise complement.
- 4In languages with infinite-width integers (Python) you must mask
~n & 0xFFFFFFFF— bare~nproduces a negative number with infinite leading 1s. - 5In Java use a long (
0xFFFFFFFFL) so the result fits the unsigned 32-bit range without sign issues.
Use this pattern when
- Compute the bitwise complement within a fixed bit width
- Toggle a known set of bits in one operation via XOR
- Translate 'unsigned NOT' into a masked operation
- Any constant-width bit inversion
Choose another pattern when
- You need to flip only some bits → XOR with a targeted mask, not all ones
- Width is not fixed / arbitrary precision → define the mask explicitly each time
- You need to count or locate set bits → popcount, not inversion
- Signed two's-complement semantics required → be careful, plain ~ may suffice
Interview takeaway
Flipping all bits in a fixed width is one XOR with an all-ones mask of that width. Remember 0xFFFFFFFF = 4294967295, mask in Python, and use long in Java — then it's a single O(1) operation, no per-bit loop.
Continue
Transfer the pattern to another problem
Use a direct variation or pattern sibling to prove the idea is reusable.
Transferable patternFixed-width bitwise complement. To invert all bits within a known width, XOR with an all-ones mask of that width (0xFFFFFFFF for 32 bits), which also equals subtracting from the all-ones ceiling. The recurring subtlety is integer width and signedness, not the algorithm.
Practice queueDirect variations and pattern siblings
Direct follow-ups