|
| 1 | +""" |
| 2 | +Calculates the sum of two non-negative integers using bitwise operators |
| 3 | +Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number |
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +def bitwise_addition_recursive(number: int, other_number: int) -> int: |
| 8 | + """ |
| 9 | + >>> bitwise_addition_recursive(4, 5) |
| 10 | + 9 |
| 11 | + >>> bitwise_addition_recursive(8, 9) |
| 12 | + 17 |
| 13 | + >>> bitwise_addition_recursive(0, 4) |
| 14 | + 4 |
| 15 | + >>> bitwise_addition_recursive(4.5, 9) |
| 16 | + Traceback (most recent call last): |
| 17 | + ... |
| 18 | + TypeError: Both arguments MUST be integers! |
| 19 | + >>> bitwise_addition_recursive('4', 9) |
| 20 | + Traceback (most recent call last): |
| 21 | + ... |
| 22 | + TypeError: Both arguments MUST be integers! |
| 23 | + >>> bitwise_addition_recursive('4.5', 9) |
| 24 | + Traceback (most recent call last): |
| 25 | + ... |
| 26 | + TypeError: Both arguments MUST be integers! |
| 27 | + >>> bitwise_addition_recursive(-1, 9) |
| 28 | + Traceback (most recent call last): |
| 29 | + ... |
| 30 | + ValueError: Both arguments MUST be non-negative! |
| 31 | + >>> bitwise_addition_recursive(1, -9) |
| 32 | + Traceback (most recent call last): |
| 33 | + ... |
| 34 | + ValueError: Both arguments MUST be non-negative! |
| 35 | + """ |
| 36 | + |
| 37 | + if not isinstance(number, int) or not isinstance(other_number, int): |
| 38 | + raise TypeError("Both arguments MUST be integers!") |
| 39 | + |
| 40 | + if number < 0 or other_number < 0: |
| 41 | + raise ValueError("Both arguments MUST be non-negative!") |
| 42 | + |
| 43 | + bitwise_sum = number ^ other_number |
| 44 | + carry = number & other_number |
| 45 | + |
| 46 | + if carry == 0: |
| 47 | + return bitwise_sum |
| 48 | + |
| 49 | + return bitwise_addition_recursive(bitwise_sum, carry << 1) |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + import doctest |
| 54 | + |
| 55 | + doctest.testmod() |
0 commit comments