標籤:賦值 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交換兩個數的常見方法及效率測試