Repository navigation
Expand file tree
/
Copy patha-b-problem.py
More file actions
58 lines (52 loc) · 1.65 KB
/
Copy patha-b-problem.py
File metadata and controls
58 lines (52 loc) · 1.65 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
import sys
class Solution:
"""
@param a: The first integer
@param b: The second integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
# write your code here, try to do it without arithmetic operators.
method = "seq"
if method == "xor":
while b > 0:
sum = a^b
carry = (a&b)<<1
a = sum
b = carry
return sum
elif method == "seq": #todo : http://stackoverflow.com/questions/37135106/what-is-good-way-to-negate-an-integer-in-binary-operation-in-python
len = sys.getsizeof(a)
mask_sign = 1<<(len-1)
neg = False
if ((a<0 and b>0 and abs(a)>abs(b)) or (a>0 and b<0 and abs(a)<abs(b)) or (a<0 and b<0)):
a = -a
b = -b
neg = True
carry = 0
sum = 0
mask = 1
while mask < mask_sign or mask < mask_sign:
cur_a = a & mask
cur_b = b & mask
if cur_a == mask and cur_b == mask:
if carry == 1:
sum |= mask
carry = 1
elif cur_a ==mask or cur_b ==mask:
if carry == 1:
carry = 1
else:
sum |= mask
carry = 0
else:
if carry:
sum |= mask
carry = 0
mask <<= 1
if neg:
sum = -sum
return sum
s = Solution()
res = s.aplusb(-2,-5)
print(res)