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

推荐订阅源

B
Blog RSS Feed
B
Blog
N
Netflix TechBlog - Medium
量子位
月光博客
月光博客
博客园_首页
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
M
MIT News - Artificial intelligence
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
腾讯CDC
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG
L
LangChain Blog
GbyAI
GbyAI
IT之家
IT之家
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理

博客园 - 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具有可逆性。