Swap two variables without intermediate variable

 

# swap two variables without intermediate variable, but intermediate variable is applicable to various situations(even with complex objects)
# the two methods below only applicable to numerics

# solution 1
a = 10
b = 8

a = a + b
b = a - b
a = a - b

print(f'{a=!r}\t{b=!r}')

# solution 2 exclusive OR
a = 10
b = 8

a = a ^ b # hold info about different bits of the two numbers
b = a ^ b
a = a ^ b
print(f'{a=!r}\t{b=!r}')
posted @ 2022-11-09 01:21  ascertain  阅读(12)  评论(0)    收藏  举报