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.
1function getSum(a, b) {
2 while (b !== 0) {
3 let carry = a & b;
4 a = a ^ b;
5 b = carry << 1;
6 }
7 return a;
8}
9
10console.log(getSum(1, 2));
JavaScript, with its dynamic typing, handles integers gracefully. The method is consistent: XOR for sum without carry, AND for determining carry, and left shift to add carried value to the next higher place value.
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.
1using System;
2
3class Program {
4 static int GetSum(int a, int b) {
5 if (b == 0) return a;
6 int sum = a ^ b;
7 int carry = (a & b) << 1;
8 return GetSum(sum, carry);
9 }
10
11 static void Main() {
12 Console.WriteLine(GetSum(2, 3));
13 }
14}
The C# code uses recursion to replace the iterative approach, applying bitwise operations for sum and carry and recursively progressing until carry is zero.