|
| 1 | +""" |
| 2 | +Swap two integers without using a temporary variable or arithmetic operators. |
| 3 | +
|
| 4 | +This implementation relies on the properties of the bitwise XOR (exclusive OR) |
| 5 | +operator. XOR-ing two values twice with the same operand restores the original |
| 6 | +value, which makes it possible to exchange two integers without allocating an |
| 7 | +extra variable or performing arithmetic. |
| 8 | +
|
| 9 | +https://en.wikipedia.org/wiki/Bitwise_operation#XOR |
| 10 | +""" |
| 11 | + |
| 12 | + |
| 13 | +def swap_without_temp(first: int, second: int) -> tuple[int, int]: |
| 14 | + """Return ``second`` and ``first`` without using a temporary variable. |
| 15 | +
|
| 16 | + >>> swap_without_temp(3, 7) |
| 17 | + (7, 3) |
| 18 | + >>> swap_without_temp(-5, 12) |
| 19 | + (12, -5) |
| 20 | + >>> swap_without_temp(0, 0) |
| 21 | + (0, 0) |
| 22 | + >>> swap_without_temp(2**31 - 1, -2**31) |
| 23 | + (-2147483648, 2147483647) |
| 24 | + >>> swap_without_temp(True, 1) |
| 25 | + Traceback (most recent call last): |
| 26 | + ... |
| 27 | + TypeError: swap_without_temp expects two integers |
| 28 | + >>> swap_without_temp(1.5, 2) |
| 29 | + Traceback (most recent call last): |
| 30 | + ... |
| 31 | + TypeError: swap_without_temp expects two integers |
| 32 | + """ |
| 33 | + |
| 34 | + if type(first) is not int or type(second) is not int: |
| 35 | + raise TypeError("swap_without_temp expects two integers") |
| 36 | + |
| 37 | + if first == second: |
| 38 | + return first, second |
| 39 | + |
| 40 | + first ^= second |
| 41 | + second ^= first |
| 42 | + first ^= second |
| 43 | + return first, second |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + import doctest |
| 48 | + |
| 49 | + doctest.testmod() |
0 commit comments