小技巧--交换两个数 2022-01-14 17:56 交换两个数的3种方法: ```java package com.example.demo.core.Test; /** * @author: HanXu * on 2022/1/14 * Class description: 交换两个数 */ public class SwapNumDemo { public static void main(String[] args) { int a = 2; int b = 5; swap1(a, b); swap2(a, b); swap3(a, b); } public static void swap1(int a, int b) { //1、异或 交换的原理:a ^ a = 0; a ^ 0 = a //只适用于整数交换 //x = x; 则 x = x ^ y ^ y a = a ^ b; b = a ^ b;//b = old a ^ b ^ b = old a a = a ^ b;//a = old a ^ old b ^ old a = old b System.out.println(a); System.out.println(b); } public static void swap2(int a, int b) { //2、加减法 //适用于数值型 a = a + b; b = a - b; // a + b - b = a a = a - b;//a + b - a = b System.out.println(a); System.out.println(b); } public static void swap3(int a, int b) { //3、追尾法,因其书写方式特别像追尾 //适用于所有类型 int c = a; a = b; b = c; System.out.println(a); System.out.println(b); } } ``` --END--
发表评论