什么时候交换两个数字而不使用第三个变量? [英] When would you swap two numbers without using a third variable?
问题描述
我已经阅读了几个资源,讨论如何交换两个数字,而不使用第三个变量。这些是最相关的几个:
- 如何在不使用任何if条件,转换或其他变量的情况下交换两个整数变量? li>
- Potential Problem inSwapping values of two variables without using a third variable
- 在不使用第三个变量的情况下交换两个整数
- http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable /
我理解为什么在大多数情况下使用描述的方法没有意义:代码变得混乱并且难以读取,并且通常比使用第三temp变量的解决方案执行得更慢。然而,我没有发现任何问题讨论双变量方法在实践中的任何好处。
在这种情况下,这一点它只是一个整洁的技巧。速度 - 如果它是有意义的,虽然你的编译器将识别一个正常交换和适当地优化(但不保证它会识别奇怪 xor
并适当优化)。
I have read several sources that discuss how to swap two numbers without using a third variable. These are a few of the most relevant:
- How do you swap two integer variables without using any if conditions, casting, or additional variables?
- Potential Problem in "Swapping values of two variables without using a third variable"
- Swap two integers without using a third variable
- http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/
I understand why it doesn't make sense to use the described methods in most cases: the code becomes cluttered and difficult to read and will usually execute more slowly than a solution utilizing a third "temp" variable. However, none of the questions I have found discuss any benefits of the two-variable methods in practice. Do they have any redeeming qualities or benefits(historical or contemporary), or are they only useful as obscure programming trivia?
At this point it's just a neat trick. Speed-wise if it makes sense though your compiler will recognize a normal swap and optimize it appropriately (but no guarantees that it will recognize weird xor
ing and optimize that appropriately).
这篇关于什么时候交换两个数字而不使用第三个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!