Java Puzzlers筆記--puzzle 7: Swap Meat ^符號問題

public class CleverSwap{
 public static void main(String[] args){
  int x = 1984;
  int y = 2001;
  x ^= y ^=x ^= y;
  System.out.println("x= " + x + "; y = " + y);
 }
}

Solution:
 顯示:x = 0; y = 1984;
 要使用中間變量
TID:
 Swap variables without a temporary - Don't do this;
 operands of operators are evaluated from left to right;
 Do not assign to the same variable more than once in a single expression;
 avoid clever programming tricks;

Correctly:
 int tmp1 = x;
 int tmp2 = y;
 int tmp3 = x^y;
 x = tmp3;
 y = tmp2 ^ tmp3;
 x = tmp1 ^ y; 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章