交换期间堆栈溢出
我们如何在不使用第三个变量的情况下处理两个变量交换期间发生的溢出。 我相信 XOR 解决方案只能用于整数。 其他变量类型呢?
How can we take care of the overflow happening during swapping of two variables without using a third variable. I believe the XOR solution can be used only for integers. what about other variable types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这不是答案,但不适合评论。
在什么情况下,您的运行距离如此接近可用堆栈存储的边缘,以至于额外使用临时变量进行交换会给您带来困难?
我可以看到一些嵌入式场景,但我很难想象一个场景,在这种情况下,堆栈空间如此紧张,这很重要(您不使用汇编语言编写代码)。
This isn't an answer but it doesn't fit in a comment.
Under what circumstances would you be running so close to the edge of your available stack storage that the additional use of a temporary variable for the swap is going to cause you difficulties?
I could see some embedded scenarios, but I'm hard pressed to imagine a scenario where you'd be so tight on stack space that this would matter (where you're not writing code in assembly language).
XOR 适用于任何您可以让 XOR 运算符处理的内容; 它是二进制数据的属性,而不是用于表示整数的二进制数据的属性。
XOR will work for anything you can get your XOR operator to process; it's a property of binary data, not of binary data used to represent integers.
根本不做。 XOR 交换算法是一个很酷的技巧。 它不应在生产代码中使用。
By not doing it at all. The XOR swap algorithm is cool hack. It shouldn't be used in production code.
XOR 解决方案适用于任何可以按位复制的类型,而不仅仅是整数。 但是,不要将变量与其自身进行异或:即
The XOR solution works with any type that can be bitwise copied, not just integers. However, do not XOR a variable with itself: i.e.
XCHG? 不需要堆栈,没有溢出(进位标志)? 设置任一:)。
What's wrong with XCHG? No stack needed, no overflow(carry flag)? set either :).
这适用于整数和浮点数。
This will work for integers and float.