LeetCode #338. Counting Bits
題目:計算a,b的加總,但是禁止使用 +、- 符號。

設A=4(0100),B=5(0101)。
1.對A與B值做 or ,得0001
2.對A與B值做 and 然後將 and 的部份進位,得0100,進位(左移1000)。
3.將新A值(0001)與新B值(1000)做or,得(1001)。
4.將新A值(0001)與新B值(1000)做and,得(0000)。
5.進位已完成(已達到0(0000))。
6.結果為1001(9),計算完成。
public class Solution {
public int GetSum(int a, int b)
{
int temp = 0;
while (b != 0)
{
temp = a ^ b;
b = a & b;
b = b << 1;
a = temp;
}
return a;
}
}
本頁面為一點點累積學習寫程式之路。
許多資訊不是正確、或只是自己看的懂得。
如果不小心點進來誤導了您,還真的不好意思。