scala交换数组相邻两位_Scala程序交换两个数字

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交换数组相邻两位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值