Is there any possiblty to swap three numbers in a single statement
Eg :
- a = 10
- b = 20
- c = 30
I want values to be changed as per the following list
a = 20
b = 30
c = 10
Can these values be transferred in a single line?
Is there any possiblty to swap three numbers in a single statement
Eg :
I want values to be changed as per the following list
a = 20
b = 30
c = 10
Can these values be transferred in a single line?
This is a silly question. But here is the only answer (so far) that is both well-defined C and truly a single line:
Uses the XOR swap algorithm, correctly.
Note: This assumes that
a
,b
andc
are all of the same integer type (the question doesn't specify).Um, I like these logic things, my solution:
BTW: I tested that (Actually using JS) and working with any numbers :)
Edit:
I tested with negative & decimals and working too :)
Since you didn't specify the language, I will pick one of my choice. It's Ruby.
Make use of the comma operator ...
Solution in C#. Using xor swap
a
andb
first. The result of the assignment is the assigned value, in this caseb
is the leftmost variable so it is return as a result of(b ^= a ^ (a ^= b ^= a))
. Then swapc
and theb
using the same algorithm. :)Try Different scenario: Eg :
For
n
number's,