Home > Java > javaTutorial > body text

Three ways to exchange values

巴扎黑
Release: 2016-12-02 09:37:26
Original
1335 people have browsed it

package com.demo.algorithm.sort;
public class NumberSwap {
/**
* 通过中间值进行交换
* @param a
* @param b
*/
public static void swap1(int a,int b){
int tmp=a;
a=b;
b=tmp;
display(a, b);
}
/**
* 两数求和然后相减的方式进行交换,x、y过大有可能超出int的最大值
* @param a
* @param b
*/
public static void swap2(int a,int b){
a=a+b;
b=a-b;
a=a-b;
display(a, b);
}
/**
* 原理:一个数异或同一个数两次,结果还是那个数
* @param a
* @param b
*/
public static void swap3(int a,int b){
a=a^b;
b=a^b;//a^b^b
a=a^b;//a^b^a^b^b
display(a, b);
}
public static void display(int a,int b){
System.out.println("a="+a+",b="+b);
}
public static void main(String[] args) {
swap1(5, 8);
swap2(5, 8);
swap3(5, 8);
}
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!