Created
May 7, 2019 03:14
-
-
Save lepig/abf9a5c29f8c17e065a4506645fbb08c to your computer and use it in GitHub Desktop.
不借助第三方变量交换2个变量的值
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| func main() { | |
| a,b := 10,20 | |
| a,b = swapNumOne(a,b) | |
| fmt.Println("第一种:", a,b) | |
| a,b = 10,20 | |
| a,b = swapNumTwo(a,b) | |
| fmt.Println("第二种:", a,b) | |
| a,b = 10,20 | |
| a,b = swapNumThree(a,b) | |
| fmt.Println("第三种:", a, b) | |
| } | |
| // 通过golang自带的语法 | |
| func swapNumOne(a,b int) (int,int) { | |
| a,b = b,a | |
| return a,b | |
| } | |
| // 算术和 | |
| func swapNumTwo(a,b int) (int,int) { | |
| a = a + b // 30 | |
| b = a - b // 10 | |
| a = a - b // 20 | |
| return a,b | |
| } | |
| // 异或位运算 参考了: https://my.oschina.net/icngor/blog/515905 | |
| func swapNumThree(a,b int) (int,int) { | |
| a = a ^ b | |
| b = a ^ b | |
| a = a ^ b | |
| return a,b | |
| } | |
| //output: | |
| 第一种: 20 10 | |
| 第二种: 20 10 | |
| 第三种: 20 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment