-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
78 lines (70 loc) · 1.76 KB
/
main.cpp
File metadata and controls
78 lines (70 loc) · 1.76 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Source: https://leetcode.com/problems/sum-of-two-integers
// Title: Sum of Two Integers
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given two integers `a` and `b`, return the sum of the two integers without using the operators `+` and `-`.
//
// **Example 1:**
//
// ```
// Input: a = 1, b = 2
// Output: 3
// ```
//
// **Example 2:**
//
// ```
// Input: a = 2, b = 3
// Output: 5
// ```
//
// **Constraints:**
//
// - `-1000 <= a, b <= 1000`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include <tuple>
using namespace std;
// ALU
//
// Let x = abs(a) and y = abs(b), we compute to x+y or x-y for non-negative integers.
// WLOG, assume x >= y.
//
// We use the following recursion to solve.
// For addition, we have x+y = x^y + (x&y << 1). (x&y are carry bits)
// For substraction, we have x-y = x^y - ((~x)&y << 1) ((~x)&y are the borrow bits)
class Solution {
public:
int getSum(int a, int b) {
int x = abs(a), y = abs(b);
// Ensure x >= y
if (x < y) {
swap(a, b);
swap(x, y);
}
if (a * b >= 0) { // same sign, x+y
while (y) {
tie(x, y) = forward_as_tuple(x ^ y, (x & y) << 1);
}
} else { // different sign, x-y
while (y) {
tie(x, y) = forward_as_tuple(x ^ y, ((~x) & y) << 1);
}
}
return a >= 0 ? x : -x;
}
};
// ALU
//
// Since we are using C++, we dan't need to care about the sign.
class Solution2 {
public:
int getSum(int a, int b) {
while (b) {
tie(a, b) = forward_as_tuple(a ^ b, (a & b) << 1);
}
return a;
}
};