如何在java中不使用临时变量交换两个数字
时间:2020-02-23 14:34:24 来源:igfitidea点击:
在本教程中,我们将看到如何在不使用临时变量的情况下交换两个数字。
有三种方法可以做到这一点。
Java程序:
package org.igi.theitroad; class SwapingTwoNumbers { public static void main(String args[]){ int a = 5; int b = 10; //First way System.out.println("First way"); System.out.println("Before swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); a = a+b; b = a-b; a = a-b; System.out.println("After swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); //Second way System.out.println(""); System.out.println("Second way"); System.out.println("Before swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); a = a*b; b = a/b; a = a/b; System.out.println("After swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); //Third way System.out.println(""); System.out.println("Third way"); System.out.println("Before swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); a = a^b; b = a^b; a = a^b; System.out.println("After swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); } }
运行上面的程序时,我们将获取以下输出:
First way Before swap: a value: 5 b value: 10 After swap: a value: 10 b value: 5 Second way Before swap: a value: 10 b value: 5 After swap: a value: 5 b value: 10 Third way Before swap: a value: 5 b value: 10 After swap: a value: 10 b value: 5
第三种方式是最快的。