zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Swap two variables without intermediate variable

two variables variable swap Without
2023-09-11 14:16:15 时间

 

# 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}')