-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfTwoIntegers.py
More file actions
94 lines (84 loc) · 2.42 KB
/
SumOfTwoIntegers.py
File metadata and controls
94 lines (84 loc) · 2.42 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
"""
def plus(x,y):
carry = 0
place = 1
ans = 0
while x > 0 and y > 0:
xdigit = x%2
ydigit = y%2
thisdigit = xdigit^ydigit^carry
carry = 1 if (xdigit & ydigit)|(xdigit & carry)|(ydigit & carry) else 0
thisdigit *= place
ans ^= thisdigit
place <<= 1
x //= 2
y //= 2
while x > 0:
temp = (x%2 ^ carry) * place
ans ^= temp
place <<= 1
carry = 1 if x%2 & carry else 0
x //= 2
while y > 0:
temp = (y%2 ^ carry) * place
ans ^= temp
place <<= 1
carry = 1 if y%2 & carry else 0
y //= 2
return ans
def minus(larger,smaller):
print(larger,"minus",smaller)
mask = 1
place = 1
ans = 0
while larger > 0 and smaller > 0:
ldigit = larger % 2
sdigit = smaller % 2
if not mask:
if ldigit: mask = 1
ldigit ^= mask
temp = (ldigit ^ sdigit) * place
ans ^= temp
place <<= 1
larger //= 2
smaller //= 2
while larger > 0:
ldigit = larger % 2
if not mask:
if ldigit: mask = 1
ldigit ^= mask
temp = ldigit * place
ans ^= temp
place <<= 1
larger //= 2
return ans
astr = bin(a)
bstr = bin(b)
if astr[0] == "-" and bstr[0] == "-":
return -1 * plus(abs(a),abs(b))
elif astr[0] == "-":
if abs(a) > b:
return -1 * minus(abs(a),b)
else:
return minus(b,abs(a))
elif bstr[0] == "-":
if abs(b) > a:
return -1 * minus(abs(b),a)
else:
return minus(a,abs(b))
return plus(a,b)
"""
MY Solution:
"""
"""
Fastest Solution ():
Smallest Memory ():
"""