// 面试题65:不用加减乘除做加法 // 题目:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、×、÷ // 四则运算符号。 #include <cstdio> int Add(int num1, int num2) { int sum = 0; //和 int carry = 0; //进位 do { sum = (num1 ^ num2); //位异或求和, 无进位 carry = (num1 & num2) << 1; //产生进位的位置左移1 num1 = sum; num2 = carry; } while (num2 != 0); //问题转换为sum和进位carry的求和问题,当不产生进位时跳出 return num1; }
// ====================测试代码==================== void Test(int num1, int num2, int expected) { int result = Add(num1, num2); if (result == expected) printf("%d + %d is %d. Passed ", num1, num2, result); else printf("%d + %d is %d. FAILED ", num1, num2, result); } int main(int argc, char* argv[]) { Test(1, 2, 3); Test(111, 899, 1010); Test(-1, 2, 1); Test(1, -2, -1); Test(3, 0, 3); Test(0, -4, -4); Test(-2, -8, -10); return 0; }
分析:分析过程很重要。
class Solution { public: int Add(int num1, int num2) { int sum = 0; int carry = 0; do { sum = (num1 ^ num2); carry = (num1 & num2) << 1; num1 = sum; num2 = carry; } while (num2 != 0); return num1; } };