php 在php中不使用第三个变量的情况下交换两个变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18356437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swap two variables value without using third variable in php
提问by Jay
I want to share 1 question which is asked most of the time in interviews and I wasn't able to e answer that question, but finally I found the answer:
我想分享 1 个在面试中大部分时间都会被问到的问题,但我无法回答这个问题,但最后我找到了答案:
How to Swap 2 variable value without using 3rd variable??
如何在不使用第三个变量的情况下交换 2 个变量值?
回答by Jay
This method will work for any variable type:
此方法适用于任何变量类型:
$a = 5;
$b = 6;
list($a, $b) = array($b, $a);
print $a . ',' . $b;
Output:
输出:
6,5
Another simple way (which only works for numbers, not strings/arrays/etc) is
另一种简单的方法(仅适用于数字,不适用于字符串/数组/等)是
$a = $a + $b; // 5 + 6 = 11
$b = $a - $b; // 11 - 6 = 5
$a = $a - $b; // 11 - 5 = 6
print $a . ',' . $b;
Output:
输出:
6,5
回答by Brian Agnew
Surely you want the XOR swap algorithm? At least for numeric variables.
你肯定想要XOR 交换算法吗?至少对于数字变量。
Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:
X := X XOR Y
Y := X XOR Y
X := X XOR Y
传统的交换需要使用临时存储变量。但是,使用 XOR 交换算法,不需要临时存储。算法如下:
X := X 异或 Y
Y := X 异或 Y
X := X 异或 Y
Although I've never seen it used in real scenarios (beyond assembler work)
虽然我从未见过它在实际场景中使用过(除了汇编工作之外)