Permutation using two variables is not three?

Possible duplicate:
Switching two values โ€‹โ€‹of variables without using a third variable

we have

int a=4;
int b=7;

Can I replace these no.s without using a third variable?

+3
source share
4 answers
a=a+b;
b=a-b;
a=a-b;
+3
source

The exact implementation of the course depends on the programming language you are using, but check out XOR swap .

An example in C might 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;
}

:. , , , , , , . .

+2

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

B = AB; // a = 11, b4

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

or

a = a * b;

B = a / b;

a = b / a;

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

+1
source

Of course: a,b = b,aworks in different programming languages.

In others, you can use the xor trick .

0
source

Source: https://habr.com/ru/post/1766203/