
Sponsored
Sponsored
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.
1using System;
2
3class Program {
4 static int GetSum(int a, int b) {
5 while (b != 0) {
6 int carry = a & b;
7 a = a ^ b;
8 b = carry << 1;
9 }
10 return a;
11 }
12
13 static void Main() {
14 Console.WriteLine(GetSum(2, 3));
15 }
16}The C# implementation also uses a loop to calculate the carry and interim sums until the carry is zero. This process relies on essential bitwise operations to replace the '+' operator.
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.
int getSum(int a, int b) {
if (b == 0) return a;
int sum = a ^ b;
int carry = (a & b) << 1;
return getSum(sum, carry);
}
int main() {
int a = 2, b = 3;
std::cout << getSum(a, b);
return 0;
}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.