Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two numbers without + operator (Clarification)

Tags:

I know that we can use the logic of binary adder where Sum = a XOR b and Carry = a AND b

I have also got a solution:

int add(int a, int b) {      if(b == 0)          return sum;      sum = a ^ b;      carry = (a & b) << 1;      return add(sum,carry); } 

What I don't understand here is why is the carry bit shifted, or multiplied by 2 during each recursion?

like image 687
noMAD Avatar asked Jan 30 '12 21:01

noMAD


People also ask

How do you find the sum of two numbers without using any operator?

We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in printf() can be used to find the sum of two numbers.

How do you sum without an operator?

Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits.

How can add two numbers without using operator in PHP?

Adding in Simple Code Two numbers can be added by passing input value in the form but without using (+) operator.


1 Answers

I find this a bit tricky to explain, but here's an attempt; think bit by bit addition, there are only 4 cases;

0+0=0  0+1=1  1+0=1  1+1=0 (and generates carry) 

The two lines handle different cases

sum = a ^ b 

Handles case 0+1 and 1+0, sum will contain the simple case, all bit positions that add up to 1.

carry = (a & b) << 1 

The (a & b) part finds all bit positions with the case 1+1. Since the addition results in 0, it's the carry that's important, and it's shifted to the next position to the left (<<1). The carry needs to be added to that position, so the algorithm runs again.

The algorithm repeats until there are no more carries, in which case sum will contain the correct result.

Btw, return sum should be return a, then both sum and carry could be regular local variables.

like image 97
Joachim Isaksson Avatar answered Sep 19 '22 05:09

Joachim Isaksson