Swap Three Numbers In Single Statement

2020-06-12 03:38发布

问题:

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?

回答1:

I found another solution for this question.

You can use this in many languages like C,C++ and Java.

It will work for float and long also.

a=(a+b+c) - (b=c) - (c=a);


回答2:

$ python
>>> a, b, c = 10, 20, 30
>>> print a, b, c
10 20 30
>>> a, b, c = b, c, a
>>> print a, b, c
20 30 10


回答3:

This is a silly question. But here is the only answer (so far) that is both well-defined C and truly a single line:

a ^= b, b ^= a, a ^= b, b ^= c, c ^= b, b ^= c;

Uses the XOR swap algorithm, correctly.

Note: This assumes that a, b and c are all of the same integer type (the question doesn't specify).



回答4:

Solution in C#. Using xor swap a and b first. The result of the assignment is the assigned value, in this case b is the leftmost variable so it is return as a result of (b ^= a ^ (a ^= b ^= a)). Then swap c and the b using the same algorithm. :)

            int a = 10;
            int b = 20;
            int c = 30;
            c ^= (b ^= a ^ (a ^= b ^= a)) ^ (b ^= c ^= b);


回答5:

Make use of the comma operator ...

a = 10;
b = 20;
c = 30;
/* one statement */
tmp = a, a = b, b = c, c = tmp; /* assumes tmp has been declared */
assert(a == 20);
assert(b == 30);
assert(c == 10);


回答6:

Um, I like these logic things, my solution:

a= b+c-((b=c)+(c=a))+c;

BTW: I tested that (Actually using JS) and working with any numbers :)

Edit:

I tested with negative & decimals and working too :)



回答7:

Since you didn't specify the language, I will pick one of my choice. It's Ruby.

sergio@soviet-russia$ irb
1.9.3p0 :001 > a = 10
 => 10 
1.9.3p0 :002 > b = 20
 => 20 
1.9.3p0 :003 > c = 30
 => 30 
1.9.3p0 :004 > a, b, c = b, c, a # <== transfer is happening here
 => [20, 30, 10] 
1.9.3p0 :005 > a
 => 20 
1.9.3p0 :006 > b
 => 30 
1.9.3p0 :007 > c
 => 10


回答8:

Try Different scenario: Eg :

a = 10
b = 20
c = 30

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

For n number's,

a = 10
b = 20
c = 30
.
.
.
n


a= a+b+c+......+n;
b=a-b-c-.......-n;
c=a-b-c-.......-n;
.
.
.
n=a-b-c-.......-n;
a=a-b-c-.......-n;


标签: c logic