Categories
Programming

Switch two integer values without using additional memory

Cool trick. Useful to know beyond just interviews.
Register_1 = Register_1 + Register_2;
Register_2 = Register_2 –  Register_1;
Register_1 = Register_1 – Register_2;
Starting
1) R1=A
2) R2=B
R1 = R1 + R2
1) A+ B
2) B
R2 = R2 – R1
1)A +B
2) A+ B – B = A
R1 = R1 – R2
1) A+B -A = B
2) A
Done
1)R1=B
2)R2=A

One reply on “Switch two integer values without using additional memory”

Great trick, there is a small mistake above. Register2 = Register1 – Register2. Here is some C code i used to test it.

include

unsigned int R1, R2;

void printRegisters(){
printf(“R1=%c (%d) R2=%c (%d)\n”, R1, R1, R2, R2);
}

int main(){

R1 = ‘A’;
R2 = ‘B’;

printRegisters();

R1 = R1 + R2;
printRegisters();

R2 = R1 – R2;
printRegisters();

R1 = R1 – R2;
printRegisters();

return 0;
}

Leave a Reply