我们讨论了解决问题的不同方法 交换两个不带临时变量的整数 .如何在不使用库函数的情况下切换到一行? 1) Python: 在Python中,有一个简单且语法简洁的结构来交换变量,我们只需要编写“x,y=y,x”。 2) C/C++: 下面是一个通常提供的经典解决方案:
// Swap using bitwise XOR (Wrong Solution in C/C++)x ^= y ^= x ^= y;
上述解决方案在C/C++中是错误的,因为它会导致未定义的行为(编译器可以以任何方式进行操作)。原因是,在表达式中多次修改变量会导致未定义的行为(如果没有) 序列点 在修改之间。 然而,我们可以使用逗号来引入序列点。因此,修改后的解决方案是
// Swap using bitwise XOR (Correct Solution in C/C++)// sequence point introduced using comma.(x ^= y), (y ^= x), (x ^= y);
3) 爪哇: 在Java中,子表达式求值的规则是明确定义的。左操作数的求值始终先于右操作数。在Java中,表达式“x^=y^=x^=y无法根据Java规则生成正确的结果。它使x=0。但是,我们可以使用“x=x^y^(y=x);”注意,表达式是从左到右计算的。如果x=5,y=10,则表达式相当于“x=5^10^(y=5);”。请注意,我们不能像在C/C++中那样在C/C++中使用它,它没有定义左操作数或右操作数是由任何运算符执行的(请参见 这 更多细节)。
4) JavaScript: 使用销毁赋值,我们可以简单地用这一行实现交换。
[x,y]=[y,x]
C
// C program to swap two variables in single line #include <stdio.h> int main() { int x = 5, y = 10; (x ^= y), (y ^= x), (x ^= y); printf ( "After Swapping values of x and y are %d %d" , x, y); return 0; } |
C++
// C++ code to swap using XOR #include <bits/stdc++.h> using namespace std; int main() { int x = 5, y = 10; // Code to swap 'x' and 'y' // to swap two numbers in one // line x = x ^ y, y = x ^ y, x = x ^ y; // printing the swapped variables cout << "After Swapping: x = " << x << ", y= " << y; return 0; } |
JAVA
// Java program to swap two variables in a single line class GFG { public static void main(String[] args) { int x = 5 , y = 10 ; x = x ^ y ^ (y = x); System.out.println( "After Swapping values" + " of x and y are " + x + " " + y); } } |
Python3
# Python program to swap two variables in a single line x = 5 y = 10 x, y = y, x print ( "After Swapping values of x and y are" , x, y) |
C#
// C# program to swap two // variables in single line using System; class GFG { static public void Main() { int x = 5, y = 10; x = x ^ y ^ (y = x); Console.WriteLine( "After Swapping values " + "of x and y are " + x + " " + y); } } // This code is contributed by aj_36 |
PHP
<?php // PHP program to swap two // variables in single line // Driver Code $x = 5; $y = 10; ( $x ^= $y ); ( $y ^= $x ); ( $x ^= $y ); echo "After Swapping values of x and y are " , $x , " " , $y ; // This code is contributed by Vishal Tripathi ?> |
Javascript
<script> // javascript program to swap two variables in single line let x = 5, y = 10; (x ^= y), (y ^= x), (x ^= y); document.write( "After Swapping values of x and y are " , x + " " , y); // This code is contributed by Surbhi Tyagi </script> |
输出
After Swapping values of x and y are 10 5
替代解决方案:
- 使用SWAP:():C++库函数
- b=(a+b)–(a=b);
- a+=b–(b=a);
- a=a*b/(b=a)
- a=a^b^(b=a)
本文由 哈希特·古普塔。 如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇关于GeekSforgek的文章 写极客。组织 .查看你在GeekSforgeks主页上的文章,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论