i tried with the following code , but i can\'t understand why it\'s giving me wrong answer. i am computing the 2\'s complement and adding with another no.
#inclu
You also can implement this recursively. In C this might look like:
#include
int add(int a, int b){
if(b == 0) return a;
int sum = a ^ b;
int carry = (a & b) << 1;
return add(sum, carry);
}
int subtract(int a, int b){
return add(a, add(~b, 1));
}
int main(){
int a = 3;
int b = 1;
int sum = add(a, b);
printf("%i + %i = %i \n", a, b, sum);
int difference = subtract(a, b);
printf("%i - %i = %i \n", a, b, difference);
return 0;
}