Question
Write a function that adds two numbers. You should not use + or any arithmetic operators.
Solution
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int accumulator_without_arithm(int m, int n)
{
if(n == 0){
return m;
}
int carry = (m & n) << 1;
int sum = m ^ n;
return accumulator_without_arithm(sum, carry);
}
int main(int argc, char* argv[])
{
for(int i = 0; i < 10; i++){
int m = rand() % 1000;
int n = rand() % 1000;
cout << m << " + " << n << " = " << accumulator_without_arithm(m, n) << endl;
}
return 0;
}
Output
41 + 467 = 508
334 + 500 = 834
169 + 724 = 893
478 + 358 = 836
962 + 464 = 1426
705 + 145 = 850
281 + 827 = 1108
961 + 491 = 1452
995 + 942 = 1937
827 + 436 = 1263