tags:

views:

1186

answers:

6

how can add two number without using + or - operators in java..

I have found one link for the same in c. http://prokutfaq.byethost15.com/AddTwoNumbersWithoutArithmetic

But, i am not able to implement in java. Please help me.

+5  A: 

As Java has bitwise operators pretty similar to the ones used in the C source you reference I wonder why a simple translation of that code doesn't "just work".

Perhaps you should explain the point at which you get stuck.

djna
+1  A: 

Remember that Java by default has sign-extending shift operators (>>). There are unsigned variants available however (>>>).

Yann Ramin
No, <<< doesn't exist, as left shift is the same for signed and unsigned.
starblue
+2  A: 

I'm not sure you've looked at the link you gave. There is a really simple way to do it with recursion. Did you try to implement this one with Java ?

#include <stdio.h>
int add(int a, int b){
    if (!a) return b;
    else
      return add((a & b) << 1, a ^ b);
}

int main(){
    printf("Enter the two numbers: \n");
    int a,b;
    scanf("%d",&a);
    scanf("%d",&b);
    printf("Sum is: %d",add(a,b));
}
Ahmet Kakıcı
+1  A: 

No matter if it is a homework or not, try this rather identical question handled earlier this week.

http://stackoverflow.com/questions/1149929/

Fredrik
I read this as "try this rather identical question HANDED IN earlier this week". Guess that makes it homework?
Matthew Schinckel
I agree it sounds like homework, the linked question was presented as an interview question which is or course almost like homework except that you are supposed to know it and not supposed to learn it.
Fredrik
+2  A: 
(int)Math.log(Math.exp(a)*Math.Exp(b))

BigInteger.valueOf(a).add(BigInteget.valueOf(b)).intValue()

?

Tom Hawtin - tackline
A: 
prem kumar