tags:

views:

213

answers:

6

Hy guys there is a 2 int variable. can u swap those int variables with out using any if conditions as well as without any casting.and u cannot use any more variables.

    ie :
    int a=10;
    int b= 5;
    always a>b;

the answer should be a=5;b=10;
A: 

yes you can do it By using plus/minus operation.

Example:
num1 = num1 + num2;                
num2 = num1 - num2;                
num1 = num1 - num2;
Pranay Rana
Better to use addition/subtraction to avoid overflows and rounding problems. That said, it's better to just use a temp variable, but still.
Dan Puzey
Multiply/Divide does not work if num2 is 0.
pascal
thanks for the info ans updated now
Pranay Rana
+4  A: 
a=a+b;
b=a-b;
a=a-b;
Doc Brown
+1  A: 

It's a little trick.

int a = 5;
int b= 10;
a = a+b;
b = a-b; /* Really (a+b) - b i.e. a */
a = a-b; /* Really (a+b) - a i.e. b */
Graphain
+1  A: 
a=a+b
b=a-b
a=a-b

That's it!

Mayur
+6  A: 

If you think you are being clever by not using 3rd variable then do some performance tests and you see that the much faster way is to use 3rd int to store the variable temporarily.

Anyways, i solved the problem with XOR bitwise operator:

a ^= b;
b ^= a;
a ^= b;
Imre L
+1  A: 

simple try this

a=a+b;
b=a-b;
a=a-b;

and that's it

Johnny