Problem Statement:
Add two given numbers without '+' operator.
Download Source Code
Solution:
We will be adding two given numbers using 'AND' and 'XOR' logical operators.
Sum of two number can be achieved with Half adder, if carry is greater than 0 , then it the process is repeated again. This is half adder implementation.
and as per full adder implementation :
Sum = 2*C + S
Below are the different ways of getting the sum using XOR and AND logical operators.
Method 1 :
Method 2:
Method 3:
Method 4:
Please post your comment and suggestions.
Happy Coding !! :)
References:
Wikipedia
Add two given numbers without '+' operator.
Download Source Code
Solution:
We will be adding two given numbers using 'AND' and 'XOR' logical operators.
![]() |
Fig: Half Adder , S: Sum and C: Carry |
Sum of two number can be achieved with Half adder, if carry is greater than 0 , then it the process is repeated again. This is half adder implementation.
and as per full adder implementation :
Sum = 2*C + S
Below are the different ways of getting the sum using XOR and AND logical operators.
Method 1 :
1 2 3 4 5 6 7 8 | int add( int a, int b) { while (b != 0 ) { int carry = a & b; a = a ^ b; b = carry << 1 ; } return a; } |
Method 2:
1 2 3 4 5 6 | int add( int a, int b) { if (b == 0 ) return a; else return add2(a ^ b, (a & b) << 1 ); } |
Method 3:
1 2 3 4 5 6 7 8 9 10 | int add( int a, int b){ int carry= a & b; int sum= a ^ b; carry = 2 * carry; sum = sum ^ carry; return sum; } |
Method 4:
1 2 3 | int add( int a, int b){ return ( 2 *( a & b) ) ^ (a ^ b); } |
Please post your comment and suggestions.
Happy Coding !! :)
References:
Wikipedia