惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
A
About on SuperTechFans
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
GbyAI
GbyAI
F
Fortinet All Blogs
Blog — PlanetScale
Blog — PlanetScale
MongoDB | Blog
MongoDB | Blog
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
H
Help Net Security
月光博客
月光博客
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
Jina AI
Jina AI
有赞技术团队
有赞技术团队
博客园_首页

博客园 - Kejames

OSQL Command. Another version for the missing method: Enum.TryParse (in C#) Form validation before onClientClick. Defining a Version String RegistryKey取得系統Media path. Enum.GetValues() About HashTable sort. 【轉載】自定義應用程序配置文件(app.config) 【轉載】二位高手所寫的OleDb Help Class [轉載]11 Visual Studio 2005 IDE Tips and Tricks to Make You a More Productive Developer [轉載]Automated Class Builder for Database Tables [轉載]HyperNetDatabase [轉載]Displaying vertical rows in a DataGrid [轉載]Generate SQL INSERT commands Programmatically [轉載]SQLDataAdapter without using SQLCommandBuilder [轉載]去除代码行号的一个小程序 網站程式安全 - 技術門檻高, 攻擊門檻低! 企業棄守!! Fiddler2 - JavaScript Beautifier Plugin Microsoft SQL Server Enterprise Manager 無法開啟的解決方式
【動腦時間】要如何交換兩個變數,而不動用第三個變數?
Kejames · 2007-09-19 · via 博客园 - Kejames

Q : 如何交換兩個變數,而不動用第三個變數?
有興趣的人可以想想...
http://www.cnblogs.com/oomusou/archive/2007/09/09/887337.html看來的文章,寫的真的很好。

以下為轉載資料。
---
這是我一個網友問我的,他說他同學去工作面試時所考的題目,一般我們要交換兩個變數會這樣寫。
C++


/* 
(C) OOMusou 2007 
http://oomusou.cnblogs.com

Filename    : swap_normal.cpp
Compiler    : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
Description : Demo how to swap 2 variable in C++
Release     : 09/08/2007 1.0
*/

#include 
<iostream>

using namespace std;

void swap(int& x, int& y) {
  
int tmp = x;
  x 
= y;
  y 
= tmp;
}


int main() {
  
int x = 1;
  
int y = 2;
  
  cout 
<< "x = " << x << ", y = " << y << endl;
  swap(x,y);
  cout 
<< "x = " << x << ", y = " << y << endl;
}


執行結果

= 1, y = 2
= 2, y = 1

假如你也這樣寫,表是你是一個很正常的coder,:D,但這樣寫還必須多一個變數tmp當暫存,能否不需tmp也能交換呢?

神奇的xor
xor全名為exclusive or,其truth table為

x y x xor y
0 0
0 1 1
1 0 1
1 1 0

簡單的說,就是當x和y不同時,其質為true。但xor最神奇的,是它具可逆性,這是其他and、or、or等邏輯做不到的。

x xor y = z
z xor y 
= x
z xor x 
= y

所以z可以看成是一個暫存變數,只要在xor x回來就可以得到y,或xor y回來等於x。

所以若要兩數交換,可以這樣寫。

= x xor y
= x xor y
= x xor y


為什麼三次xor就可以呢?以上的code原本應該寫成

= x xor y
= z xor y
= z xor y (此時y已經等於x,所以相當於z xor x)


但這樣寫多了一個變數z,且x在過程中已經不會用到了,所以將變數z放在x中,可以省下一個變數,所以就變成了

= x xor y
= x xor y
= x xor y


一切的神奇都歸因於xor具有可逆性。