当前位置:网站首页>Four methods of exchanging the values of a and B

Four methods of exchanging the values of a and B

2022-07-06 14:38:00 Wang yeqiang

In exchange for a,b Value , You may think it's very simple , But if you suddenly think of 4 Methods , Maybe the most basic method of temporary storage with the third variable appears in your mind for a moment , Now I summarize four methods :

initialization a and b:

# About python Replace  a b  It's worth it   Method 
a = 3
b = 5
print(" At the beginning of the :a = {} , b = {}".format(a,b))

1. Use the third variable c The staging :

def ChangeFirst(a,b):  # Take the third variable C The staging 
    c = a
    a = b
    b = c
    print("ChangeFirst After method exchange  :a = {} , b = {}".format(a,b))

2. Exchange sum and difference ( The staging )

def ChangeSecond(a,b): # Use sum and difference 
    a = a+b
    b = a-b
    a = a-b
    print("ChangeSecond After method exchange :a = {} , b = {}".format(a,b))

3. Using bitwise XOR :

def ChangeThird(a,b):  # Bitwise XOR ( In binary , Same as 0 Different for 1)
    a = a^b
    b = a^b
    a = a^b
    print("ChangeThird After method exchange  :a = {} , b = {}".format(a,b))

4.Python Proprietary approach :

def ChangeFourth(a,b):  #python Proprietary approach 
    a,b = b,a
    print("ChangeFourth After method exchange :a = {} , b = {}".format(a,b))

Code runs :

ChangeFirst(a,b)
ChangeSecond(a,b)
ChangeThird(a,b)
ChangeFourth(a,b)

Code output :

 

原网站

版权声明
本文为[Wang yeqiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918394649.html