Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The goal is to swap 2 numbers. The shortest code wins.

  • Temporary variables are not allowed
  • You can manipulate only one variable at a time
  • One of the variables may be 0
share|improve this question

closed as unclear what you're asking by arshajii, Jan Dvorak, Paul R, Dr. belisarius, SeanC Nov 11 '13 at 13:26

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Improperly defined. You can't do anything without a minimum amount of “language native support”, which you're not defining at all. – J B Nov 10 '13 at 14:52
    
@JB is it clear now? – Ilya_Gazman Nov 10 '13 at 14:55
1  
Not much. I'm not a fluent Mathematica user, but I'd wager one would argue that {a, b} = {b, a}; is not a native swap operation, but a simple list assignment. If you're going to restrict language facilities, you'd better be absolutely clear in what's allowed and what's not, and not rely on any form of user appreciation. – J B Nov 10 '13 at 15:00
    
@jb Point! How about now? – Ilya_Gazman Nov 10 '13 at 15:06
    
Once you manage to clear that up, you'll be left with trying to determine what we call “an objective winning criterion”. Check out our FAQ for pointers. Oh, and “longest code”, though objective, is kind of ridiculous and frowned upon. – J B Nov 10 '13 at 15:07

Ruby, 14 bytes

a^=b
b^=a
a^=b

13

a=[a,b]
b,a=c
share|improve this answer

C, 17 bytes

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

Equivalently:

a += b;
b = a - b;
a = a - b;
share|improve this answer
    
I count 17 bytes and not 7. – ProgramFOX Nov 10 '13 at 15:27
    
@ProgramFOX typing error sorry – Ilya_Gazman Nov 10 '13 at 15:28
1  
Test case: a=-1;b=-2147483648;. – primo Nov 10 '13 at 15:31
    
@primo Cool, I am going to test it. I am not sure what will happen. I think it will work anyway. – Ilya_Gazman Nov 10 '13 at 15:35
    
@primo yeah its working. A + B = 2147483647 – Ilya_Gazman Nov 10 '13 at 16:44

Bash, 27 bytes

a+=\ $b;b=${a% *};a=${a#* }

In action:

a=5 b=20
a+=\ $b;b=${a% *};a=${a#* }
printf "a='%s', b='%s'\n" "$a" "$b"
a='20', b='5'
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.