开发者

Swapping using two variables not three? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Swapping two variable value without using 3rd variable

we have

int a=4;
int b=7;
开发者_JS百科

can i swap these no.s without using third variable?


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


The precise implementation of course depends on the programming language you're using, but check out XOR swap.

An example in C could be

#include <stdio.h>

/* Swaps the content pointed to by a and b. The memory pointed to is
   assumed non-overlapping! */

void swap(int* a, int* b)
{
  *a = (*a)^(*b);
  *b = (*a)^(*b);
  *a = (*a)^(*b);
}

int main(int argc, char** argv)
{
  int a = 4;
  int b = 7;
  printf("a=%d, b=%d\n", a, b);
  swap(&a, &b);
  printf("a=%d, b=%d\n", a, b);
  return 0;
}

Important: As Prasoon Saurav commented on the question itself, this answer to another question is more correct than mine, seeing as it is important that the two variables reside at non-overlapping locations in memory. My example does not check for this.


a=a+b; //a=11,b=7

b=a-b; //a=11,b4

a=a-b; //a=7,b=4

or

a=a*b;

b=a/b;

a=b/a;

but careful with this method, overflow or underflow is possible for some combinations.


Sure: a,b = b,a works in various programming languages.

In others you can use the xor trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜