donnemartin / donnemartin/interactive-coding-challenges

Add two numbers without the + or - sign [Bug]

Open
#205 0 comments 0 reactions 0 assignees View on GitHub
needs-review
Dominant language
Python
Stars
31.8k
Forks
4.7k
PR merge metrics
No merged PRs in 30d

Description

The bitwise add 2 integers solution will hit infinite loop for negative integers. The carry will keep increasing if the bit length is not bounded.
Proposed solution:
```python
def sum_two(self,a,b):
#max bit length, change to 32 for 32bit
max_positive = 2 ** 64
min_negative = -2 ** 64

while b != 0:
if b == max_positive:
return a ^ min_negative
a,b = a ^ b,(a&b)<<1
return a
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.