面试题:交换两个变量的四种方法

112 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

今天介绍一道常见的面试题目,如何快速交换两个变量的位置,有以下四种方式。

第一种: 借助第三个变量(常用方式)

int z = x;
x = y;
y = z;

新建一个变量z,交换xy的位置。

第二种: 先加和,再减去其中一个数值b,赋值给b,最后再从和中减去b得到a

public static void main(String[] args) {
    int a = 3, b = 4;
    System.out.println("交换之前:");
    System.out.println(String.format("a=%d, b=%d", a, b));
    a = a + b;
    b = a - b;
    a = a - b;
    System.out.println("交换之后:");
    System.out.println(String.format("a=%d, b=%d", a, b));
}


交换之前:
a=3, b=4
交换之后:
a=4, b=3

第三种: 先加和,之后把a的值赋给b,最后减去b得到a,实质与方法二相同

public static void main(String[] args) {
    int a = 3, b = 4;
    System.out.println("交换之前:");
    System.out.println(String.format("a=%d, b=%d", a, b));
    a = (a + b) - (b = a);
    System.out.println("交换之后:");
    System.out.println(String.format("a=%d, b=%d", a, b));
}

交换之前:
a=3, b=4
交换之后:
a=4, b=3

第四种: 异或操作

一个数与另外一个数作两次异或操作等于数字本身,即a^b^b=a.

public static void main(String[] args) {
    int a = 3, b = 4;
    System.out.println("交换之前:");
    System.out.println(String.format("a=%d, b=%d", a, b));
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    System.out.println("交换之后:");
    System.out.println(String.format("a=%d, b=%d", a, b));
}

交换变量的题目属于常规面试题了,「常规」的原因不是在于它多简单,而是这种操作在实际编程中会经常用到,而且会比较容易考察一个人的编程基本功。所以在日常练习的时候要注意积累,好记性不如烂笔头,注意总结,总结复盘实际对于个人能力提升是一个非常重要的途径。

另外二进制操作实际也是应用非常频繁的操作,比如异或、取反等,有时间总结一篇常用的二进制操作,共勉~