Codacoda
Back to Academy

bitwise operations

Swap Without Temp

XOR swap exchanges two values without a temporary variable by exploiting XOR's self-inverse property: a ^ a = 0 and a ^ 0 = a. Three XOR operations are applied in sequence to swap values in place. While mainly a teaching tool today, it demonstrates XOR's algebraic properties.

Use Cases

  • Understanding XOR's algebraic properties
  • Embedded systems with extremely limited registers
  • Classic interview and puzzle question
  • In-place array reversal without extra memory

Complexity Analysis

MetricBestAverageWorst
TimeO(1)O(1)O(1)
SpaceO(1)

Visualization

Initiala=50000010176543210b=300000011
Speed:1x
Initial values: a=5, b=3. We will swap them using only XOR (no temporary variable).Step 1 / 4

Implementation

Output

Click "Run Code" to see output...