簡而言之,它使用y(和「carry/x & y」它變成)來修改x,直到它變成兩個整數的和。例如,
y=1 (....0001), x=anything (either .....0 or .....1)
if x ends with 0, x&y=0
//x^y = x becomes ....001 (thereby adding 1)
//since x&y=0 the loop stops
if x ends with 1, x&y=1
//x^y = x
//since y= x&y<<1, new y=(.....000010)
if x ends with 01, x&y=0
//x^y = x becomes ....010 (thereby adding 1)
//since x&y=0 the loop stops
if x ends with 11, x&y=1
//x^y = .....01
//since y= x&y<<1, new y=(......000100)
if x ends with 011
//stuff happens and x becomes ....100 (thereby adding 1)
//loop stops
if x ends with 111
//...
//if x ends with 111111, x becomes ....1000000 (thereby adding 1)
//if x ends with 1111111, x becomes ....10000000 (thereby adding 1)
//if x ends with 11111111, x becomes ....100000000 (thereby adding 1)
//well you get the idea
同樣的邏輯適用到y的所有值,並且是沒有太大從正常除了不同之處僅在於現在有2個可能的位(0和1),而不是通常10(0到9)。
這是一個[全加器](https://en.wikipedia.org/wiki/Adder_%28electronics%29#Full_adder)。在你向左移動32次後,將會有32個零位(它是'0')。 –
@ElliottFrisch Well ... yes))。但沒有解釋它爲什麼起作用。 – Alupkers
@Alupkers你問爲什麼算法停止?正如@ElliottFrisch所說:'curry << 1'將最右邊的位設置爲0.在最多32步(整數是Java中的32位寬)中,所有位都是0,因此'y == 0'並且循環結束。 – Nikem