1. Swapping
The following piece of code is what I discovered by a glance to what my deskmate was reading:
It is about swapping and I think it can be applied to all kinds of data swapping if there is no high-level requirements involved. Until then, I was convinced that a temporary variable is inevitable in even the swapping of the simplest type. Although ccomplishing it without a temporary variable is probably the only merit of this code, it is very clever and inspiring.
The conventional way of swapping two entities:
- voidswap(inoutTa,inoutTb)
- {
- Tt=b;
- b=a;
- a=t;
- }
The improved method:
- voidswap(inoutTa,inoutTb) // T supports ^ operation in the bitwise sense
- {
- a ^= b;
- b ^= a;
- a ^= b;
- }
Yes, it's that simple and easy to remember, just three XORs, despite its obscurity.
本文介绍了一种不使用临时变量进行数据交换的方法,通过位操作实现两个变量的交换,这种方法不仅简单且易于记忆,只需三个异或(XOR)操作即可完成。文章对比了传统交换方法与改进后的交换方法,并详细解释了其工作原理。
1万+

被折叠的 条评论
为什么被折叠?



