6

There are two integer variables. Can you swap those integer variables without using any if conditions, without casting, and without using additional variables? For example:

int a = 10;
int b = 5;

a > b always. The answer should be a == 5 and b == 10

9
  • 5
    No, I have no idea how to slow down a problem or make it go faster. Commented Jul 16, 2010 at 6:29
  • seems to be a homework assignment if that's the case you should tag it as such Commented Jul 16, 2010 at 6:29
  • 3
    Duplicate: stackoverflow.com/questions/804706/… Commented Jul 16, 2010 at 6:30
  • can u solve this problem Commented Jul 16, 2010 at 6:30
  • 7
    Isn't it lovely, when someone upvotes a homework duplicate? :P Commented Jul 16, 2010 at 6:36

6 Answers 6

14

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;
Sign up to request clarification or add additional context in comments.

7 Comments

More about swapping with xor is here en.wikipedia.org/wiki/XOR_swap_algorithm
This fails to work if a == b.
What language are you using?
@Axoren: no, it does not fail.
Your example "fails" because you have the variables pointing to same memory location. This is not in the scope of question
|
11
a=a+b;
b=a-b;
a=a-b;

Comments

4

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 */

Comments

3

simple try this

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

and that's it

Comments

3

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

Example:
num1 = num1 + num2;                
num2 = num1 - num2;                
num1 = num1 - num2;

3 Comments

Better to use addition/subtraction to avoid overflows and rounding problems. That said, it's better to just use a temp variable, but still.
Multiply/Divide does not work if num2 is 0.
thanks for the info ans updated now
3
a=a+b
b=a-b
a=a-b

That's it!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.