您的位置:首页 > 编程语言 > Java开发

Java Puzzlers笔记--puzzle 7: Swap Meat ^符号问题

2007-03-03 19:13 435 查看
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; 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java variables string class