-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum_of_two_integers.cpp
More file actions
53 lines (48 loc) · 1.1 KB
/
sum_of_two_integers.cpp
File metadata and controls
53 lines (48 loc) · 1.1 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
/*
* =====================================================================================
*
* Filename: sum_of_two_integers.cpp
*
* Description: Sum of Two Integers. Calculate the sum of two integers a and b, but
* you are not allowed to use the operator + and -.
*
* Version: 1.0
* Created: 03/04/19 12:37:37
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
class Solution
{
public:
int getSum(int a, int b)
{
int sum = 0;
while (b != 0)
{
sum = a ^ b;
b = (unsigned int)(a & b) << 1;
a = sum;
}
return sum;
}
};
int main(int argc, char* argv[])
{
int a = 1;
int b = 2;
if (argc > 2)
{
a = atoi(argv[1]);
b = atoi(argv[2]);
}
int sum = Solution().getSum(a, b);
printf("(%d) + (%d) = %d\n", a, b, sum);
return 0;
}