@Rajeev: When you add two one-bit quantities, you get a two-bit
result:
0 + 0 = 00, 0 + 1 = 01, 1 + 0 = 01, and 1 + 1 = 10.
Note that the leftmost bit of sum of the the single-bit quantities A
and B, obeys the logic A & B, and the rightmost bit obeys A ^ B, where
& is the logical AND operation and ^ is the logical eXclusive OR
operation. When adding a multibit binary number, the leftmost bit
carries into the next bit position. So the code you presented just
does the multibit addition using the above two rules on all bits in
parallel. The first two statements determine the results using the
"leftmost bit" and "rightmost bit" rules above. If there are any
carries, then they must be added to the next position to the left.
Thus, shift the carries left one bit and repeat the addition process
using the leftmost and rightmost bit rules again. Do this until there
are no remaining carries. Hope this helps.

Dave

On Dec 31, 6:19 am, rajeev kumar <rajeevprasa...@gmail.com> wrote:
> Can any one tell me how to add two numbers using bitwise operators only.
>
> After spending so much time on googling,i found the below java code.But is
> is confusing.
> <algogeeks@googlegroups.com>public class AddTwoNumbers {
>
>     private static int myAdd(int a, int b)
>     {
>         int carry = a & b;
>         int result = a ^ b;
>         while(carry != 0)
>         {
>             int shiftedcarry = carry << 1;
>             carry = result & shiftedcarry;
>             result ^= shiftedcarry;
>         }
>         return result;
>     }
>
>     public static void main(String[] args){
>          System.out.println(myAdd(4, 5));
>     }
>
> }
>
> Please explain it.
>
> --
> Thank You
> Rajeev Kumar

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algoge...@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?hl=en.

Reply via email to