java(引入一個中間變數,不引入中間變數)交換兩個變數的值

來源:互聯網
上載者:User

標籤:java   不引入變數交換兩個數   原始碼   兩數交換   引入一個中間變數   

一、描述

在不引入其它變數的情況下交換兩個數,引入一個變數做中介,交換兩個數的值。

二、原始碼

<span style="font-size:18px;">package tong.yue.sort;public class SwapTwoValues {/** * @param args */public static void main(String[] args) {int a = 10,b = 20;swapByExtraVariable(a,b);swapBySelf(a,b);//這裡採用值傳遞,只是複製一個a,b的副本去參加函數的運算,並不影響main函數中原來的a和b的值System.out.println("main function: a="+a+",b="+b);}private static void swapBySelf(int a, int b) {// 在不引入其它變數的情況下交換兩個數,利用兩數之和來做a = a+b;   //a儲存兩數之和b = a-b;//兩數之和-b,即為aa = a-b;//兩數之和-b,此時的b已經變成了a,所以相當於sum-a=bSystem.out.println("swapBySelf first function:a="+a+",b="+b);//還有另一種方法,利用兩數之差,即兩數之間的距離a = b-a;   //a=兩者的差b = b-a;//b = 原來的b-兩數的距離==原來的aa = a+b;//最終的a=兩者之差+原來的a==原來的bSystem.out.println("swapBySelf second function:a="+a+",b="+b);//又換回來了}private static void swapByExtraVariable(int a, int b) {// 引入一個變數做中介,交換兩個數int temp = a;a = b;b = temp;System.out.println("swapByExtraVariable function:a="+a+",b="+b);}}</span>

三、運行結果


java(引入一個中間變數,不引入中間變數)交換兩個變數的值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.