// Interview question 65: Addition without addition, subtraction, multiplication, and division // Topic: Write a function to find the sum of two integers. It is required that +,-, ×, ÷ // four arithmetic symbols should not be used in the function body . #include <cstdio> int Add ( int num1, int num2) { int sum = 0 ; // and int carry = 0 ; // carry do { sum = (num1 ^ num2); // bit XOR sum, none Carry carry = (num1 & num2) << 1 ; // The position where the carry is generated is shifted to the left by 1 num1 = sum; num2 = carry; } while (num2! = 0 ); // The problem is converted to the sum problem of sum and carry carry, and return num1; }
// ====================测试代码==================== void Test(int num1, int num2, int expected) { int result = Add(num1, num2); if (result == expected) printf("%d + %d is %d. Passed\n", num1, num2, result); else printf("%d + %d is %d. FAILED\n", 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; }
Analysis: The analysis process is important.
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; } };