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

java算法4~交换两个整数,不能使用任何额外的变量

2016-11-28 13:20 323 查看
算法目的:交换两个整数;

算法要求:不使用任何额外的变量;

算法思路:使用位运算,异或操作。

实现如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package algorithm_database;

/**
*
* 交换两个整数,不使用任何额外的变量
*/
public class ChangeTwoInteger {

public static void main(String[] args){

int a = 4; //4就是0100
int b = 9; //9就是1001

a = a^b; //a就是1101 现在异或的结果1101就代表a和b的位不同的信息,这样写是因为算法实现有要求,不能用额外变量,否则用int c = a^b会好理解一点。
b = a^b; //b就是0100 为4,其实就是变成了当初的a
a = a^b; //a就是1001 为9,其实就是用b(即当初的a)异或1101得到最终的a(即当初的b)

System.out.println(a);
System.out.println(b);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java算法
相关文章推荐