Dadas dos variables n1 y n2. La tarea es intercambiar los valores de ambas variables sin usar la tercera variable.
Ejemplos:
X : 10 Y : 20 After swapping X and Y, we get : X : 20 Y : 10
Python
# Python code to swap two numbers # without using another variable x = 5 y = 7 print ("Before swapping: ") print("Value of x : ", x, " and y : ", y) # code to swap 'x' and 'y' x, y = y, x print ("After swapping: ") print("Value of x : ", x, " and y : ", y)
Python
# Python code to swap two numbers # using Bitwise XOR method x = 5 # x = 0101 y = 10 # y = 1010 print ("Before swapping: ") print("Value of x : ", x, " and y : ", y) # Swap code x ^= y # x = 1111, y = 1010 y ^= x # y = 0101, x = 1111 x ^= y # x = 1010, y = 0101 print ("After swapping: ") print("Value of x : ", x, " and y : ", y)
Python
# Python code to swap two numbers # using + and - operators x = 5.4 y = 10.3 print ("Before swapping: ") print("Value of x : ", x, " and y : ", y) # Swap code x = x + y # x = 15.7, y = 10.3 y = x - y # x = 15.7, y = 5.4 x = x - y # x = 10.3, y = 5.4 print ("After swapping: ") print("Value of x : ", x, " and y : ", y)
Python
# Python code to swap two numbers # using / and * operators x = 5.4 y = 10.3 print ("Before swapping: ") print("Value of x : ", x, " and y : ", y) # Swap code x = x * y # x = 55.62, y = 10.3 y = x / y # x = 55.62, y = 5.4 x = x / y # x = 10.3, y = 5.4 print ("After swapping: ") print("Value of x : ", x, " and y : ", y)
Python3
# python program to swap two numbers # using bitwise addition for swapping x = 5; y = 10; print ("Before swapping: ") ; print("Value of x : ", x, " and y : ", y) ; # same as x = x + y x = (x & y) + (x|y) ; #vsame as y = x - y y = x + (~y) + 1 ; # same as x = x - y x = x + (~y) + 1 ; print ("After swapping: ") print("Value of x : ", x, " and y : ", y) # This code is contributed by bunnyram19
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA