不用额外变量交换两个整数的值

不用额外变量交换两个整数的值

题目

  如何不用任何额外变量交换两个整数的值?

解答

  使用位运算的异或运算,或者使用加法运算

  a异或b的结果是c,那么c就是a整数位信息和b整数位信息的所有不同信息。

a = a^b,当前a=c;b = a^b相当于b = c^b 当前b=a;a = a^b 相当于a = c^a 当前a=b,完成交换;

如果是加法交换的话,假设a + b结果是c,那么

a = a+b,当前a=c;b = a-b相当于b = c-b 当前b=a;a = a-b 相当于a = c-a 当前a=b,完成交换;

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int a = s.nextInt();
		int b = s.nextInt();
		int[] n = exchangeWei(a, b);
		int[] m = exchangeJia(a, b);
		System.out.println("ab原值     :a = " + a + "  " + "b = " + a);
		System.out.println("位 运 算   :a = " + n[0] + "  " + "b = " + n[1]);
		System.out.println("加法运算:a = " + m[0] + "  " + "b = " + m[1]);
	}

	public static int[] exchangeWei(int a, int b) {
		int[] n = new int[2];
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		n[0] = a;
		n[1] = b;
		return n;
	}

	public static int[] exchangeJia(int a, int b) {
		int[] n = new int[2];
		a = a + b;
		b = a - b;
		a = a - b;
		n[0] = a;
		n[1] = b;
		return n;
	}

}

运算结果如下:

1 2
ab原值  :a = 1  b = 1
位 运 算:a = 2  b = 1
加法运算:a = 2  b = 1



    原文作者:菜鸟闯天下zxl
    原文地址: https://blog.csdn.net/u010456903/article/details/48901347
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞