同事問到的一題,不用加減法來計算加減法,當然是使用bit operation來操作,這題的想法主要是處理進位問題。
這邊只用recursive來處理,將進位的結果再加回去。
但須注意recursive可能的深度,避免function call stack overflow。(但以32bit整數加法來說 最多呼叫32次)。 事實上此處的recursive是在最尾端(tail recursive),所以在有處理tail call elimination的語言或是compiler有處理tail call optimization則不需擔心深度問題
#include <iostream>
int add(int a, int b)
{
int r = a ^ b;
int c = (a & b) << 1;
if(!c) return r;
return add(r, c);
}
int sub(int a, int b)
{
int r = a ^ b;
int c = (r & b) << 1;
if(!c) return r;
return sub(r, c);
}
int main()
{
std::cout << add(-2, 34) << "," << sub(-2, 34) << std::endl;
return 0;
}