一、前置理论
位异或-->>同0异1
- bit位的值相同,结果为0
- bit位的值不同,结果为1
用 12^9 这个栗子(博主有强迫症,引入 hutool-all 依赖包)
import cn.hutool.core.util.StrUtil;
import org.junit.Test;
public class BitTest {
@Test
public void testXOR() {
// 00000000000000000000000000001100
System.out.println(StrUtil.padPre(Integer.toBinaryString(12), 32,'0'));
// 00000000000000000000000000001001
System.out.println(StrUtil.padPre(Integer.toBinaryString(9), 32,'0'));
// 00000000000000000000000000000101
System.out.println(StrUtil.padPre(Integer.toBinaryString(12^9), 32,'0'));
}
}
| 十进制 | 二进制(简化版) |
|---|---|
| 12 | 1100 |
| 9 | 1001 |
| 5 | 0101 |
从左到右,分别对 bit 进行比较
- 1^1=0
- 1^0=1
- 0^0=0
- 0^1=1
位异或的特点
- 0异或任何数等于任何数,即0^a=0
- 任何数异或自己等于0,即a^a=0
二、可以解决什么问题?
找出数组中的单身狗数字(只有一个数字出现1次,其它数字出现了偶次数)