JZ-C-47
剑指offer第四十七题:不能用加减乘除做加法
1 //============================================================================ 2 // Name : JZ-C-47.cpp 3 // Author : Laughing_Lz 4 // Version : 5 // Copyright : All Right Reserved 6 // Description : 不能用加减乘除做加法 7 //============================================================================ 8 9 #include <iostream> 10 #include <stdio.h> 11 using namespace std; 12 13 int Add(int num1, int num2) { 14 int sum, carry; 15 do { 16 sum = num1 ^ num2; //第一步:异或(各(★)位相加,先不考虑进位) 17 carry = (num1 & num2) << 1; //第二步:先与运算再左移得到进位 18 19 num1 = sum; 20 num2 = carry; 21 } while (num2 != 0); //第三步:前两个步骤的结果相加(重复前面两步,直到不产生进位为止) 22 23 return num1; 24 } 25 26 // ====================测试代码==================== 27 void Test(int num1, int num2, int expected) { 28 int result = Add(num1, num2); 29 if (result == expected) 30 printf("%d + %d is %d. Passed\n", num1, num2, result); 31 else 32 printf("%d + %d is %d. Failed\n", num1, num2, result); 33 } 34 35 int main(int argc, char** argv) { 36 Test(1, 2, 3); 37 Test(111, 899, 1010); 38 Test(-1, 2, 1); 39 Test(1, -2, -1); 40 Test(3, 0, 3); 41 Test(0, -4, -4); 42 Test(-2, -8, -10); 43 }
—————————————————————————————————————行走在人猿的并行线——Laughing_Lz