C++ Code to Add two numbers without using + operator
#include <iostream>
#include <math.h>
using namespace std;
int add(int a,int b)
{
int num=0,carry=0,p=0;
int abit,bbit,numbit;
while(a!=0||b!=0)
{
abit=a&1;
bbit=b&1;
numbit=abit^bbit^carry;
carry=(abit&bbit)||(abit&carry)||(bbit&carry);
num=num+numbit*(int)pow(2,p);
p++;
a=a>>1;
b=b>>1;
}
if(carry==1)
num=num+(int)pow(2,p);
return num;
}
int main(int argc, char *argv[])
{
printf("%d",add(70,40));
return 0;
}
Output :
110
No comments:
Post a Comment