This approach imitates the addition mechanism in digital circuits using bitwise operations. The key operations involved are:
Time Complexity: O(n), where n is the number of bits needed to represent the numbers.
Space Complexity: O(1), constant space usage.
1def get_sum(a, b):
2 while b != 0:
3 carry = a & b
4 a = a ^ b
5 b = carry << 1
6 return a
7
8print(get_sum(2, 3))
Python, being a high-level language, allows easy manipulation of integers. The approach and logic are the same: use ^
for interim sum and &
followed by a << 1 for updating the carry.
This approach is an extension of the iterative bitwise method but uses recursive calls to achieve the result. Instead of using a loop, it relies on recursive function calls to process the sum and carry until the carry becomes zero.
Time Complexity: O(n), where n is the number of bits.
Space Complexity: O(n), due to the recursive call stack.
1#include <iostream>
2
3int getSum(int a, int b) {
4 if (b == 0) return a;
5 int sum = a ^ b;
6 int carry = (a & b) << 1;
7 return getSum(sum, carry);
8}
9
10int main() {
11 int a = 2, b = 3;
12 std::cout << getSum(a, b);
13 return 0;
14}
The C++ recursive approach mirrors the iterative bitwise approach, handling base cases and recursive progression similarly. It stops recursion when there's no carry left to add.