Skip to content
Merged
Changes from 3 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
57 changes: 57 additions & 0 deletions maths/sum_of_two_positive_numbers_bitwise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""
Calculates the sum of two positive numbers using bitwise operator
Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number
"""


def sum_of_two_positive_numbers_bitwise(number: int, other_number: int) -> int:
""" "
>>> sum_of_two_positive_numbers_bitwise(4, 5)
9
>>> sum_of_two_positive_numbers_bitwise(8, 9)
17
>>> sum_of_two_positive_numbers_bitwise(0, 4)
4
>>> sum_of_two_positive_numbers_bitwise(4.5, 9)
Traceback (most recent call last):
...
TypeError: Both parameters MUST be in integer type!
>>> sum_of_two_positive_numbers_bitwise('4', 9)
Traceback (most recent call last):
...
TypeError: Both parameters MUST be in integer type!
>>> sum_of_two_positive_numbers_bitwise('4.5', 9)
Traceback (most recent call last):
...
TypeError: Both parameters MUST be in integer type!
>>> sum_of_two_positive_numbers_bitwise(-1, 9)
Traceback (most recent call last):
...
ValueError: Both parameters MUST be in positive value!
>>> sum_of_two_positive_numbers_bitwise(1, -9)
Traceback (most recent call last):
...
ValueError: Both parameters MUST be in positive value!
"""

if isinstance(number, int) is False or isinstance(other_number, int) is False:
raise TypeError("Both parameters MUST be in integer type!")

if number < 0 or other_number < 0:
raise ValueError("Both parameters MUST be in positive value!")

# Base case
sum = number ^ other_number
carry = number & other_number

if (carry) == 0:
return sum

# Recursive case
return sum_of_two_positive_numbers_bitwise(sum, carry << 1)


if __name__ == "__main__":
import doctest

doctest.testmod()