Add two numbers without using arithmetic operators | GeeksforGeeks
Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.
http://www.acmerblog.com/jiudu-1507-2391.html
http://www.cnblogs.com/easonliu/p/4238634.html
int add(int x, int y){
int a,b;
do{
a = x & y;// a holds the carry (a承接进位)
b = x ^ y;// b holds the sum without carry (b承接无进位的和)
x = a<<1; // perform carry, x becomes carry (进位,并用x承接进位)
y = b;
}while(x) // until carry = 0 (直到无进位)
return y;
}
http://algorithmsforever.blogspot.com/2011/11/tricky-addition.html
Read full article from Add two numbers without using arithmetic operators | GeeksforGeeks
Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.
int Add(int x, int y){ // Iterate till there is no carry while (y != 0) { // carry now contains common set bits of x and y int carry = x & y; // Sum of bits of x and y where at least one of the bits is not set x = x ^ y; // Carry is shifted by one so that adding it to x gives the required sum y = carry << 1; } return x;}int Add(int x, int y){ if (y == 0) return x; else return Add( x ^ y, (x & y) << 1);}05 | int fadd(int a,int b){ |
06 | int ans,up; |
07 | int num1 = a; |
08 | int num2 = b; |
09 | do{ |
10 | ans = num1 ^ num2; |
11 | up = (num1 & num2) << 1; |
12 | num1 = ans; |
13 | num2 = up; |
14 | }while(up != 0); |
15 | return ans; |
16 | } |
3 int add(int a, int b) { 4 int n1, n2; 5 do { 6 n1 = a ^ b; 7 n2 = (a & b) << 1; 8 9 a = n1; 10 b = n2; 11 } while (n2 != 0); 12 13 return n1; 14 }http://siyang2notleetcode.blogspot.com/2015/02/add-two-number-using-bit-operation.html
int add(int x, int y){
int a,b;
do{
a = x & y;// a holds the carry (a承接进位)
b = x ^ y;// b holds the sum without carry (b承接无进位的和)
x = a<<1; // perform carry, x becomes carry (进位,并用x承接进位)
y = b;
}while(x) // until carry = 0 (直到无进位)
return y;
}
http://algorithmsforever.blogspot.com/2011/11/tricky-addition.html
Read full article from Add two numbers without using arithmetic operators | GeeksforGeeks