Swap Three Numbers In Single Statement

2020-06-12 02:57发布

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?

标签: c logic
8条回答
淡お忘
2楼-- · 2020-06-12 03:28

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).

查看更多
迷人小祖宗
3楼-- · 2020-06-12 03:29

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 :)

查看更多
Ridiculous、
4楼-- · 2020-06-12 03:32

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
查看更多
相关推荐>>
5楼-- · 2020-06-12 03:40

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);
查看更多
一纸荒年 Trace。
6楼-- · 2020-06-12 03:43

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);
查看更多
一夜七次
7楼-- · 2020-06-12 03:48

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;
查看更多
登录 后发表回答