什么时候交换两个数字而不使用第三个变量? [英] When would you swap two numbers without using a third variable?

查看:277
本文介绍了什么时候交换两个数字而不使用第三个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几个资源,讨论如何交换两个数字,而不使用第三个变量。这些是最相关的几个:





我理解为什么在大多数情况下使用描述的方法没有意义:代码变得混乱并且难以读取,并且通常比使用第三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:

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 xoring and optimize that appropriately).

这篇关于什么时候交换两个数字而不使用第三个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆