java exchange operator temp

时间:2012-07-21 18:58:37

标签: java

我正在尝试理解如何写下面涉及交换/交换运算符的语句的逻辑。到目前为止,我已经谷歌搜索并搜索了文本(解决问题的java介绍)。之前有没有人在以下方面苦苦挣扎并且可能找到了答案(这是关于字符串的一个例子,但我正在努力使用临时运算符使用temp):

  

有两个String变量s1和s2已经被声明和初始化。写一些交换价值的代码。

我知道我应该使用临时变量,这正是我的逻辑为空的地方。

我写它的方式,我知道它的错误如下:

temp = s1;
s2 = temp;

4 个答案:

答案 0 :(得分:3)

在错误的解决方案中,您失去了s2的价值。您希望使用temp 保留任一变量的值,以便在交换期间不会丢失该值。

以下列出了您需要做的事情:

  • 复制某处s1的值。
  • 现在,如果隐藏了s1的副本,您可以将s1的值分配给s2
  • 现在将s2的副本分配给s1

答案 1 :(得分:2)

为了完整起见,当您不需要临时变量时,有一种特殊情况。

如果要交换的两个值长度相等且语言允许您对它们使用按位运算符,则可以执行XOR swap

A = A bitwise xor B
B = A bitwise xor B
A = A bitwise xor B

虽然在现代计算机上这很难实用,但了解和展示XOR操作的一个有趣方面是很好的。

答案 2 :(得分:0)

将变量视为只能容纳一件事的容器。要交换两个变量的值,您需要三个容器。

String s1 = "Some string", s2 = "Another string", tmp;
tmp = s1; // put the first item into the third bin
s1 = s2; // put the second item into the first bin
s2 = tmp; // put the first item into the second item

答案 3 :(得分:0)

所有语言:

temp = s1; // temporarily store the s1 value because we'll replace it next
s1 = s2; // now s1 lost it's value, and got a new one
s2 = temp; // luckily s2 doesn't go home empty handed, the temp is still good