scala交换数组相邻两位
Given two numbers, we have to swap them.
给定两个数字,我们必须交换它们。
Example:
例:
Input:
a = 10
b = 20
Output:
a = 20
b = 10
1)使用第三个变量交换两个数字 (1) Swapping two numbers using third variable)
To swap two values, there is a simple approach is using a temporary variable that stores the element for swapping.
要交换两个值,有一种简单的方法是使用一个临时变量来存储要交换的元素。
Algorithm:
算法:
Let, variable a contains first value, variable b contains second value and temp is the temporary variable.
设变量a包含第一个值,变量b包含第二个值,而temp是临时变量。
Step 1: temp = a
Step 2: a = b
Step 3: b = temp
Program:
程序:
object myObject {
def main(args: Array[String]) {
var a = 10
var b = 20
println("Values before swapping:\t a= " + a + ", b= " + b)
// swapping
var temp = a
a = b
b = temp
println("Values after swapping:\t a= " + a + ", b= " + b)
}
}
Output
输出量
Values before swapping: a= 10, b= 20
Values after swapping: a= 20, b= 10
2)交换两个数字而不使用第三个变量 (2) Swapping two numbers without using third variable)
We can also swap two numbers without using the third variable. This method saves computation space hence is more effective.
我们也可以交换两个数字而无需使用第三个变量。 该方法节省了计算空间,因此更加有效。
Let, variable a contains first value, variable b contains second value.
设变量a包含第一个值,变量b包含第二个值。
Step 1: a = a + b
Step 2: a = a - b
Step 3: b = a - b
Program:
程序:
object myObject {
def main(args: Array[String]) {
var a = 10
var b = 20
println("Values before swapping:\t a= " + a + ", b= " + b)
// swapping
a = a + b
b = a - b
a = a - b
println("Values after swapping:\t a= " + a + ", b= " + b)
}
}
Output
输出量
Values before swapping: a= 10, b= 20
Values after swapping: a= 20, b= 10
翻译自: https://www.includehelp.com/scala/swap-two-numbers.aspx
scala交换数组相邻两位