java交換兩個數的常見方法及效率測試

來源:互聯網
上載者:User

標籤:賦值   java   效率   交換   elong   

原文地址——http://blog.csdn.net/qq525099302/article/details/47294443

論兩個數的交換的重要性

討論交換兩個數的方法對某些人來說無聊,但某些人很樂意探究,甚至某些面試官喜歡用這個做文章。剛出來找工作筆試的時候我也碰到與之相關的問題。

常見的兩個數交換的方法
  • 邊賦值邊運算
  • 加減減交換
  • 用中間變數交換
  • 異或交換
下面是代碼
public class Test {    public static void main(String[] args) {        long start,end;         int a = 100000, b = 200000, t;        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 邊賦值邊運算——462            a = b + (b = a) * 0;        }        end = System.currentTimeMillis();        System.out.println(end - start);        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 加減減交換——898            a += b;            b = a - b;            a -= b;        }        end = System.currentTimeMillis();        System.out.println(end - start);        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 用中間變數交換——449            t = a;            a = b;            b = t;        }        end = System.currentTimeMillis();        System.out.println(end - start);        start = System.currentTimeMillis();        for (int i = 0; i <= 1000000000; i++) {// 異或交換——896            a ^= b;            b ^= a;            a ^= b;        }        end = System.currentTimeMillis();        System.out.println(end - start);    }}
說明

注釋後面的數字是我的電腦運行10億次交換所用的時間(毫秒)

總結

如果沒有強迫症或者硬性要求,用中間變數交換是最好的方法。
如果要走非主流邊賦值邊運算是最有效率的。
加減減和異或雖然看起來挺酷的,但是運算多,慢是應該的。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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.