forked from zhedahht/CodingInterviewChinese2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.cpp
More file actions
62 lines (48 loc) · 1.37 KB
/
AddTwoNumbers.cpp
File metadata and controls
62 lines (48 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题65:不用加减乘除做加法
// 题目:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、×、÷
// 四则运算符号。
#include <cstdio>
int Add(int num1, int num2)
{
int sum, carry;
do
{
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
}
while(num2 != 0);
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;
}