Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

swift - swapping variables

I have this coding question writing in swift:

var a = 5
var b = 8

//Without touching any of the exisiting code, can you write 3 lines of 
//code to switch around the values held inside the two variables 
//a and b? And you cannot use any numbers in your code, 
//e.g. you can't just write: 

a = 8; b = 5

//write your answers here 

print("a: (a)")
print("b: (b)")

The model answer is

var c = a
a = b
b = c

Question: am I thinking in a wrong direction if my answer to this is:

a = (a+b-a)
b = (b+a-b)

I didn't think about creating a new variable at all..

question from:https://stackoverflow.com/questions/65945005/swapping-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Duncan C has already pointed out the error in the “model?answer”, and Larme has pointed out the flaw in your suggested answer, so I won't address those.

Ignoring the “3 lines” requirement, here's the shortest, and perhaps the clearest, answer:

swap(&a, &b)

This uses the standard library's swap function. Swift requires the & sigils to alert you (and anyone else reading the code) that the variables may be modified by the swap function.

Here is another correct one-line Swift solution that is more easily extended to rearrange more than just two variables:

(a, b) = (b, a)

This works because the right side is fully evaluated before any assignments are performed.

Your attempt at a ‘clever’ solution can be fixed by using three computations:

a = b - a
b = b - a        // = b0 - (b0 - a0) = b0 - b0 + a0 = a0
a = a + b        // = b0 - a0 + a0 = b0

You can find some discussion of this trick in Hacker's Delight 2nd edition section 2-20 “Exchanging Registers”.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...