# programming brainteaser

#### rainman::|:|

##### macrumors 603
Original poster
okay, a friend of mine gave me this kind of brainteaser question about programming (language non-specific): Two variables, A and B. Can you switch the values of the variables without a third variable? The hint given is to think "simple math". I've thought it over, and a couple of people with more programming experience than me are puzzled by it too. Anyone ever heard this before? She was asked it during a job interview... pnw

#### bentmywookie

##### macrumors regular
i think i have it

this was pretty interesting, i think i figured it out:

so you have two variables, A and B. In any machine these will be bit strings of some length.

Here is what I came up with:
Given A and B,

A = A XOR B (where XOR returns the XOR of each bit)

B = A AND NOT B (by this i mean, for each bit, if A is set to 1 and B is set to 0, then return 1, otherwise return 0) - doing this puts the value of A in B

A = A AND NOT B (since B is now equal to original A, this will give you the value of B)

now here's the real question . . . was this question posed in a microsoft interview? i know they like to ask questions like these.

#### Sun Baked

##### macrumors G5
1 Add A0 to B0 store in B, A=A0 & B=(B0 + A0)

2 Subtract A from B store in A, A=B0 & B=B0+A0

3 Subtract A from B store in B, A=B0 & B=A0

Unless I reversed my signs, like somebody did on the last math quiz. #### GeeYouEye

##### macrumors 68000
Sure
a = a + b
b = b - a
b = abs(b)
a = a - b

a = 10
b = 5

a = 10 + 5 (15)
b = 5 - 15 (-10)
b = abs(-10) (10)
a = 15 - 10 (5)

a = 5
b = 10

Register on MacRumors! This sidebar will go away, and you'll see fewer ads.