Page 1 of 1
Swap two number variables without using a temp third
Posted: Thu Jun 02, 2011 11:53 am
by MachineCode
Today I read how to swap two number variables without using a temp third. This is much slower than using PureBasic's "Swap" command, and doesn't take data type limits into account, which is why I didn't post it as a "tip"; but I think it's cool anyway. I never knew it could be done by maths like this. Does anyone know any other ways?
Code: Select all
a=12345
b=67890
a+b : b=a-b : a-b
Debug a
Debug b
Re: Swap two number variables without using a temp third
Posted: Thu Jun 02, 2011 10:29 pm
by idle
Can't say that it occurred to me to swap that way with add and subtract
you can do the same with or and xor
Code: Select all
a=12345
b=67890
a|b : b!a : a!b
Debug a
Debug b
Re: Swap two number variables without using a temp third
Posted: Sun Jun 05, 2011 6:56 pm
by graph100
remain the problem of the high number
if the sum is higher than the type allow.
Re: Swap two number variables without using a temp third
Posted: Sun Jun 05, 2011 6:57 pm
by eesau
Code: Select all
A = 1
B = 2
; Let's swap them without using a temp third variable
B = 1
A = 2
