Add Without Plus
17.1 Add Without Plus: Write a function that adds two numbers. You should not use + or any arithmetic operators.
Implemented a full adder from scratch (min SOP through K-maps)
// initially I pushed back the bits into a vector
// this isnt the entire solution to the problem
// I've left the sum vector for learning purposes when I look back
// full adder
vector<int> sum(int a, int b) {
int c_in = 0;
vector<int> c_out;
vector<int> sum;
int s;
int temp;
int count = 0;
c_out.push_back(c_in);
int bit_a, bit_b;
while (b != 0 || a != 0) {
// look only at first bit
bit_a = a & 1;
bit_b = b & 1;
// add bits using min SOP
/*
sum.push_back((!bit_a && bit_b && !c_out.at(count)) ||
(!bit_a && !bit_b && c_out.at(count)) ||
(bit_a && !bit_b && !c_out.at(count)) ||
(bit_a && bit_b && c_out.at(count)));
*/
// equivalent
sum.push_back(bit_a ^ bit_b ^ c_out.at(count));
// find next c_out
c_out.push_back((bit_b && c_out.at(count)) || (bit_a && bit_b) || (bit_a && c_out.at(count)));
count++;
// look at next bit
a = a >> 1; b = b >> 1;
}
// add final carry
sum.push_back(c_out.at(count));
return sum;
}
// clean version
int add(int a, int b) {
int c_in, c_out, s, final_s, base;
c_in = c_out = final_s = base = 0;
// s = current bit sum
// final_s = current bit sum + previous sum
int bit_a, bit_b;
while (b != 0 || a != 0) {
// look only at first bit
bit_a = a & 1;
bit_b = b & 1;
// sum bits
s = bit_a ^ bit_b ^ c_out;
// find next c_out
c_out = (bit_b && c_out) || (bit_a && bit_b) || (bit_a && c_out);
// concatinate current bit to prev bit to form an actual number with significant base
final_s = (s << base++) | final_s;
// look at next bit
a = a >> 1; b = b >> 1;
}
// add final carry
final_s = (c_out << base++) | final_s;
return final_s;
}
int main()
{
//vector<int> s = sum(10, 10);
//for (int i = s.size() - 1; i >= 0; i--) cout << s.at(i);
//cout << endl;
//s = sum(5, 10);
//for (int i = s.size() - 1; i >= 0; i--) cout << s.at(i);
//cout << endl;
//s = sum(10, 7);
//for (int i = s.size() - 1; i >= 0; i--) cout << s.at(i);
//cout << endl;
cout << add(10, 10) << endl;
cout << add(7, 10) << endl;
cout << add(20, 10) << endl;
cout << add(45, 3) << endl;
}
Last updated