Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,8 @@
* [Test Number Of One Bits](https://github.com/BrianLusina/PythonSnips/blob/master/bit_manipulation/number_of_1_bits/test_number_of_one_bits.py)
* Single Number
* [Test Single Number](https://github.com/BrianLusina/PythonSnips/blob/master/bit_manipulation/single_number/test_single_number.py)
* Sum Two Integers
* [Test Sum Of Two Integers](https://github.com/BrianLusina/PythonSnips/blob/master/bit_manipulation/sum_two_integers/test_sum_of_two_integers.py)

## Cryptography
* Atbash Cipher
Expand Down
76 changes: 76 additions & 0 deletions bit_manipulation/sum_two_integers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Sum of Two Integers

Given two integers a and b, return the sum of the two integers without using the operators + and -.


## Examples

Example 1:
```text
Input: a = 1, b = 2
Output: 3
```

Example 2:
```text
Input: a = 2, b = 3
Output: 5
```

## Constraints

- -1000 <= a, b <= 1000

## Topics

- Math
- Bit Manipulation

## Solution

We will use the bitwise manipulation pattern to calculate the sum of two integers without using the arithmetic operators.
To calculate the desired sum, we'll use the bitwise operations.

Let's dive into the logic to get a better idea of how to use bitwise operations for this task:

- Bitwise XOR (`^`) operation: This operation allows us to calculate the sum of corresponding bits in a and b without
considering the carry (if any).

- Bitwise AND (`&`) operation: The AND operation will help us determine where carry propagation is necessary. By applying
this operation to a and b, we can identify which bit positions require carry consideration.

- Iterative Process: The algorithm functions iteratively, much like how binary addition is carried out. We will start
with the least significant bits and advance toward the most significant bits of a and b. At each bit position, we
calculate the sum while considering the carry from the previous bit's addition. This ensures that any carry is
appropriately propagated throughout the process.

The algorithm to obtain the sum of the given integers is as follows:

1. To limit the result to 32-bits, we set a mask variable to `0xFFFFFFFF`.
2. Start a loop that continues while b is not equal to 0. We calculate the sum of the two integers without carrying, by
taking XOR and then AND the result with the mask.
3. For calculating the carry which needs to be added to the next pair of integers, we take the AND of a and b,
leftshifting the result by 1-bit, and then AND this result with the mask.
4. We update a and b with the new values for the next iteration, which are the result and carry calculated in steps 2
and 3, respectively.
5. At the end, to handle overflow when performing the addition of two integers, we have a condition that checks if the
result exceeds the maximum value of a signed 32-bit integer. If it does, we return the two’s complement of the result
to ensure that the returned value remains within the valid range.

![Solution 1](./images/solutions/sum_two_integers_solution_1.png)
![Solution 2](./images/solutions/sum_two_integers_solution_2.png)
![Solution 3](./images/solutions/sum_two_integers_solution_3.png)
![Solution 4](./images/solutions/sum_two_integers_solution_4.png)
![Solution 5](./images/solutions/sum_two_integers_solution_5.png)
![Solution 6](./images/solutions/sum_two_integers_solution_6.png)
![Solution 7](./images/solutions/sum_two_integers_solution_7.png)

### Time Complexity

The time complexity of this solution is O(1), because the while loop runs for a maximum of 32 times, since the integers
are represented by 32−bits. Each iteration does bitwise operations, which takes constant O(1), time hence making the
total time complexity as O(1)*O(32) = O(32), which is equivalent to O(1).

### Space Complexity

The solution uses fixed numbers of variables to compute the result. Hence the space complexity is constant. O(1).
36 changes: 36 additions & 0 deletions bit_manipulation/sum_two_integers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
def integer_addition(a: int, b: int):
# Mask to limit the result to 32-bits (the size of an integer in Python)
mask = 0xFFFFFFFF
# Setting maximum integer value
max_int = 0x7FFFFFFF

while b != 0:
# Sum of the integers without carrying
result = (a ^ b) & mask

# Calculate the carry that needs to be added to the next pair of integers
carry = ((a & b) << 1) & mask

# Update a and b to the new values for the next iteration
a = result
b = carry

# We check if the result is greater than the maximum integer value
# Return the result as is if result is not greater than max_int
if a < max_int:
return a

# If it is, then return the two's complement of the result
else:
return ~(a ^ mask)


def integer_addition_2(a: int, b: int) -> int:
mask = 0xFFFFFFFF
max_int = 2 ** 31 - 1
while b != 0:
sum_ = (a ^ b) & mask
carry = (a & b) & mask
a = sum_
b = carry << 1
return a if a <= max_int else ~(a ^ mask)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
26 changes: 26 additions & 0 deletions bit_manipulation/sum_two_integers/test_sum_of_two_integers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import unittest
from parameterized import parameterized
from bit_manipulation.sum_two_integers import integer_addition, integer_addition_2

SUM_OF_TWO_INTEGERS_TEST_CASES = [
(1, -1, 0),
(2, 5, 7),
(3, 10, 13),
(-10, -40, -50),
(13, 16, 29),
]

class SumOfTwoIntegersTestCase(unittest.TestCase):
@parameterized.expand(SUM_OF_TWO_INTEGERS_TEST_CASES)
def test_integer_addition(self, a: int, b: int, expected: int):
result = integer_addition(a, b)
self.assertEqual(result, expected)

@parameterized.expand(SUM_OF_TWO_INTEGERS_TEST_CASES)
def test_integer_addition_2(self, a: int, b: int, expected: int):
result = integer_addition_2(a, b)
self.assertEqual(result, expected)


if __name__ == '__main__':
unittest.main()
Loading