On Tue, Sep 8, 2009 at 2:09 AM, ayush chauhan <therajput.ay...@gmail.com>wrote:

> Cud u plz explain the logic behind this?

On Mon, Sep 7, 2009 at 9:44 PM, Gokul <spgo...@gmail.com> wrote:
>
> you can try this......
>      int  add(int x, int y)
>     {
>            if (!x) return y;
>            else
>                 return add((x & y) << 1, x ^ y);
>      }
>

Lets consider you want to add 34590 and 987387065 in decimal notation.
   9 8 7 6 8 7 0 6 5
+         3 4 5 5 9 0
---------------------------
   9 8 7 9 2 2 5 5 5 ----> addition of digits neglecting carry
+ 0 0 0 1 1 0 1 0 0 ---> represents carry
--------------------------
   9 8 7 0 3 2 6 5 5
+ 0 0 1 0 0 0 0 0 0
---------------------------
   9 8 8 0 3 2 6 5 5
+ 0 0 0 0 0 0 0 0 0

So ans is 988032655.

Similarly, In terms of bit representation, for addition of two numbers 'x'
and 'y', (x&y)<<1 represents the carry number and x^y represents the number
neglecting the carry. So for example let the number is 43 & 14.

x = 43 = 1 0 1 0 1 1
y = 14 = 0 0 1 1 1 0

   1 0 1 0 1 1
+ 0 0 1 1 1 0
------------------
   1 0 0 1 0 1 ---> x^y
+ 0 1 0 1 0 0 ---> (x&y)<<1
------------------
   1 1 0 0 0 1
+ 0 0 1 0 0 0
------------------
   1 1 1 0 0 1
+ 0 0 0 0 0 0
------------------

hence 43 + 14 = 111001 = 57



-- 
Shishir Mittal
Ph: +91 9936 180 121

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to