题目:给定两个整型变量a,b,在不使用其他变量的情况下,实现两个变量值的交换。
分析:采用二进制的方法。
code:
a = 1234
b = 5678
print("binary after swap, a:{0}, b:{1}".format(bin(a), bin(b)))
a = a ^ b
b = a ^b
a = a ^b
print("binary after swap, a:{0}, b:{1}".format(bin(a), bin(b)))
程序的运行结果:
binary after swap, a:0b10011010010, b:0b1011000101110
binary after swap, a:0b1011000101110, b:0b10011010010
网友评论