1. Bit-by-Bit Full Adder Simulation
Intuition
Initialize carry = 0, res = 0. For i from 0 to 31, extract bitA = (a >> i) & 1, bitB = (b >> i) & 1. Compute sumBit = bitA ^ bitB ^ carry, and update carry = (bitA & bitB) | (carry & (bitA ^ bitB)). Set bit i in res.
When to apply: When understanding gate-level computer architecture.
Algorithm
- Step 1: Set res = 0, carry = 0.
- Step 2: Loop i from 0 to 31.
- Step 3: Extract bitA, bitB.
- Step 4: sumBit = bitA ^ bitB ^ carry.
- Step 5: carry = (bitA & bitB) | (carry & (bitA ^ bitB)).
- Step 6: res |= (sumBit << i). Return res.
#include <iostream> using namespace std; int getSumFullAdder(int a, int b) { int res = 0; int carry = 0; for (int i = 0; i < 32; ++i) { int bitA = (a >> i) & 1; int bitB = (b >> i) & 1; int sumBit = bitA ^ bitB ^ carry; carry = (bitA & bitB) | (carry & (bitA ^ bitB)); res |= (sumBit << i); } return res;} int main() { cout << "Full Adder (1, 2): " << getSumFullAdder(1, 2) << endl; // 3 cout << "Full Adder (2, 3): " << getSumFullAdder(2, 3) << endl; // 5 cout << "Full Adder (-2, 3): " << getSumFullAdder(-2, 3) << endl; // 1 return 0;}Time & Space Complexity
- Time complexity:
O(32) = O(1) - Space complexity:
O(1)