原理

基本原理

0s 表示一串 0,1s 表示一串 1。

  1. x ^ 0s = x x & 0s = 0 x | 0s = x
  2. x ^ 1s = ~x x & 1s = x x | 1s = 1s
  3. x ^ x = 0 x & x = x x | x = x

利用 x ^ 1s = ~x 的特点,可以将一个数的位级表示翻转;利用 x ^ x = 0 的特点,可以将三个数中重复的两个数去除,只留下另一个数。

  1. 1^1^2 = 2

利用 x & 0s = 0 和 x & 1s = x 的特点,可以实现掩码操作。一个数 num 与 mask:00111100 进行位与操作,只保留 num 中与 mask 的 1 部分相对应的位。

  1. 01011011 &
  2. 00111100
  3. --------
  4. 00011000

利用 x | 0s = x 和 x | 1s = 1s 的特点,可以实现设值操作。一个数 num 与 mask:00111100 进行位或操作,将 num 中与 mask 的 1 部分相对应的位都设置为 1。

  1. 01011011 |
  2. 00111100
  3. --------
  4. 01111111

位与运算技巧

n&(n-1) 去除 n 的位级表示中最低的那一位 1。例如对于二进制表示 01011011,减去 1 得到 01011010,这两个数相与得到 01011010。

  1. 01011011 &
  2. 01011010
  3. --------
  4. 01011010

n&(-n) 得到 n 的位级表示中最低的那一位 1。-n 得到 n 的反码加 1,也就是 -n=~n+1。例如对于二进制表示 10110100,-n 得到 01001100,相与得到 00000100。

  1. 10110100 &
  2. 01001100
  3. --------
  4. 00000100

n-(n&(-n)) 则可以去除 n 的位级表示中最低的那一位 1,和 n&(n-1) 效果一样。

移位运算

>> n 为算术右移,相当于除以 2n,例如 -7 >> 2 = -2。

  1. 11111111111111111111111111111001 >> 2
  2. --------
  3. 11111111111111111111111111111110

>>> n 为无符号右移,左边会补上 0。例如 -7 >>> 2 = 1073741822。

  1. 11111111111111111111111111111001 >>> 2
  2. --------
  3. 00111111111111111111111111111111

<< n 为算术左移,相当于乘以 2n。-7 << 2 = -28。

  1. 11111111111111111111111111111001 << 2
  2. --------
  3. 11111111111111111111111111100100

mask 计算

要获取 111111111,将 0 取反即可,~0。

要得到只有第 i 位为 1 的 mask,将 1 向左移动 i-1 位即可,1<<(i-1) 。例如 1<<4 得到只有第 5 位为 1 的 mask :00010000。

要得到 1 到 i 位为 1 的 mask,(1<<i)-1 即可,例如将 (1<<4)-1 = 00010000-1 = 00001111。

要得到 1 到 i 位为 0 的 mask,只需将 1 到 i 位为 1 的 mask 取反,即 ~((1<<i)-1)。

Java 中的位操作

  1. static int Integer.bitCount(); // 统计 1 的数量
  2. static int Integer.highestOneBit(); // 获得最高位
  3. static String toBinaryString(int i); // 转换为二进制表示的字符串

1. 统计两个数的二进制表示有多少位不同

  1. Hamming Distance (Easy)

Leetcode / 力扣

  1. Input: x = 1, y = 4
  2. Output: 2
  3. Explanation:
  4. 1 (0 0 0 1)
  5. 4 (0 1 0 0)
  6. ↑ ↑
  7. The above arrows point to positions where the corresponding bits are different.

对两个数进行异或操作,位级表示不同的那一位为 1,统计有多少个 1 即可。

  1. public int hammingDistance(int x, int y) {
  2. int z = x ^ y;
  3. int cnt = 0;
  4. while(z != 0) {
  5. if ((z & 1) == 1) cnt++;
  6. z = z >> 1;
  7. }
  8. return cnt;
  9. }

使用 z&(z-1) 去除 z 位级表示最低的那一位。

  1. public int hammingDistance(int x, int y) {
  2. int z = x ^ y;
  3. int cnt = 0;
  4. while (z != 0) {
  5. z &= (z - 1);
  6. cnt++;
  7. }
  8. return cnt;
  9. }

可以使用 Integer.bitcount() 来统计 1 个的个数。

  1. public int hammingDistance(int x, int y) {
  2. return Integer.bitCount(x ^ y);
  3. }

2. 数组中唯一一个不重复的元素

  1. Single Number (Easy)

Leetcode / 力扣

  1. Input: [4,1,2,1,2]
  2. Output: 4

两个相同的数异或的结果为 0,对所有数进行异或操作,最后的结果就是单独出现的那个数。

  1. public int singleNumber(int[] nums) {
  2. int ret = 0;
  3. for (int n : nums) ret = ret ^ n;
  4. return ret;
  5. }

3. 找出数组中缺失的那个数

  1. Missing Number (Easy)

Leetcode / 力扣

  1. Input: [3,0,1]
  2. Output: 2

题目描述:数组元素在 0-n 之间,但是有一个数是缺失的,要求找到这个缺失的数。

  1. public int missingNumber(int[] nums) {
  2. int ret = 0;
  3. for (int i = 0; i < nums.length; i++) {
  4. ret = ret ^ i ^ nums[i];
  5. }
  6. return ret ^ nums.length;
  7. }

4. 数组中不重复的两个元素

  1. Single Number III (Medium)

Leetcode / 力扣

两个不相等的元素在位级表示上必定会有一位存在不同。

将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。

diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。

  1. public int[] singleNumber(int[] nums) {
  2. int diff = 0;
  3. for (int num : nums) diff ^= num;
  4. diff &= -diff; // 得到最右一位
  5. int[] ret = new int[2];
  6. for (int num : nums) {
  7. if ((num & diff) == 0) ret[0] ^= num;
  8. else ret[1] ^= num;
  9. }
  10. return ret;
  11. }

5. 翻转一个数的比特位

  1. Reverse Bits (Easy)

Leetcode / 力扣

  1. public int reverseBits(int n) {
  2. int ret = 0;
  3. for (int i = 0; i < 32; i++) {
  4. ret <<= 1;
  5. ret |= (n & 1);
  6. n >>>= 1;
  7. }
  8. return ret;
  9. }

如果该函数需要被调用很多次,可以将 int 拆成 4 个 byte,然后缓存 byte 对应的比特位翻转,最后再拼接起来。

  1. private static Map<Byte, Integer> cache = new HashMap<>();
  2. public int reverseBits(int n) {
  3. int ret = 0;
  4. for (int i = 0; i < 4; i++) {
  5. ret <<= 8;
  6. ret |= reverseByte((byte) (n & 0b11111111));
  7. n >>= 8;
  8. }
  9. return ret;
  10. }
  11. private int reverseByte(byte b) {
  12. if (cache.containsKey(b)) return cache.get(b);
  13. int ret = 0;
  14. byte t = b;
  15. for (int i = 0; i < 8; i++) {
  16. ret <<= 1;
  17. ret |= t & 1;
  18. t >>= 1;
  19. }
  20. cache.put(b, ret);
  21. return ret;
  22. }

6. 不用额外变量交换两个整数

程序员代码面试指南 :P317

  1. a = a ^ b;
  2. b = a ^ b;
  3. a = a ^ b;

7. 判断一个数是不是 2 的 n 次方

  1. Power of Two (Easy)

Leetcode / 力扣

二进制表示只有一个 1 存在。

  1. public boolean isPowerOfTwo(int n) {
  2. return n > 0 && Integer.bitCount(n) == 1;
  3. }

利用 1000 & 0111 == 0 这种性质,得到以下解法:

  1. public boolean isPowerOfTwo(int n) {
  2. return n > 0 && (n & (n - 1)) == 0;
  3. }

8. 判断一个数是不是 4 的 n 次方

  1. Power of Four (Easy)

Leetcode / 力扣

这种数在二进制表示中有且只有一个奇数位为 1,例如 16(10000)。

  1. public boolean isPowerOfFour(int num) {
  2. return num > 0 && (num & (num - 1)) == 0 && (num & 0b01010101010101010101010101010101) != 0;
  3. }

也可以使用正则表达式进行匹配。

  1. public boolean isPowerOfFour(int num) {
  2. return Integer.toString(num, 4).matches("10*");
  3. }

9. 判断一个数的位级表示是否不会出现连续的 0 和 1

  1. Binary Number with Alternating Bits (Easy)

Leetcode / 力扣

  1. Input: 10
  2. Output: True
  3. Explanation:
  4. The binary representation of 10 is: 1010.
  5. Input: 11
  6. Output: False
  7. Explanation:
  8. The binary representation of 11 is: 1011.

对于 1010 这种位级表示的数,把它向右移动 1 位得到 101,这两个数每个位都不同,因此异或得到的结果为 1111。

  1. public boolean hasAlternatingBits(int n) {
  2. int a = (n ^ (n >> 1));
  3. return (a & (a + 1)) == 0;
  4. }

10. 求一个数的补码

  1. Number Complement (Easy)

Leetcode / 力扣

  1. Input: 5
  2. Output: 2
  3. Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

题目描述:不考虑二进制表示中的首 0 部分。

对于 00000101,要求补码可以将它与 00000111 进行异或操作。那么问题就转换为求掩码 00000111。

  1. public int findComplement(int num) {
  2. if (num == 0) return 1;
  3. int mask = 1 << 30;
  4. while ((num & mask) == 0) mask >>= 1;
  5. mask = (mask << 1) - 1;
  6. return num ^ mask;
  7. }

可以利用 Java 的 Integer.highestOneBit() 方法来获得含有首 1 的数。

  1. public int findComplement(int num) {
  2. if (num == 0) return 1;
  3. int mask = Integer.highestOneBit(num);
  4. mask = (mask << 1) - 1;
  5. return num ^ mask;
  6. }

对于 10000000 这样的数要扩展成 11111111,可以利用以下方法:

  1. mask |= mask >> 1 11000000
  2. mask |= mask >> 2 11110000
  3. mask |= mask >> 4 11111111
  1. public int findComplement(int num) {
  2. int mask = num;
  3. mask |= mask >> 1;
  4. mask |= mask >> 2;
  5. mask |= mask >> 4;
  6. mask |= mask >> 8;
  7. mask |= mask >> 16;
  8. return (mask ^ num);
  9. }

11. 实现整数的加法

  1. Sum of Two Integers (Easy)

Leetcode / 力扣

a ^ b 表示没有考虑进位的情况下两数的和,(a & b) << 1 就是进位。

递归会终止的原因是 (a & b) << 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。

  1. public int getSum(int a, int b) {
  2. return b == 0 ? a : getSum((a ^ b), (a & b) << 1);
  3. }

12. 字符串数组最大乘积

  1. Maximum Product of Word Lengths (Medium)

Leetcode / 力扣

  1. Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
  2. Return 16
  3. The two words can be "abcw", "xtfn".

题目描述:字符串数组的字符串只含有小写字符。求解字符串数组中两个字符串长度的最大乘积,要求这两个字符串不能含有相同字符。

本题主要问题是判断两个字符串是否含相同字符,由于字符串只含有小写字符,总共 26 位,因此可以用一个 32 位的整数来存储每个字符是否出现过。

  1. public int maxProduct(String[] words) {
  2. int n = words.length;
  3. int[] val = new int[n];
  4. for (int i = 0; i < n; i++) {
  5. for (char c : words[i].toCharArray()) {
  6. val[i] |= 1 << (c - 'a');
  7. }
  8. }
  9. int ret = 0;
  10. for (int i = 0; i < n; i++) {
  11. for (int j = i + 1; j < n; j++) {
  12. if ((val[i] & val[j]) == 0) {
  13. ret = Math.max(ret, words[i].length() * words[j].length());
  14. }
  15. }
  16. }
  17. return ret;
  18. }

13. 统计从 0 ~ n 每个数的二进制表示中 1 的个数

  1. Counting Bits (Medium)

Leetcode / 力扣

对于数字 6(110),它可以看成是 4(100) 再加一个 2(10),因此 dp[i] = dp[i&(i-1)] + 1;

  1. public int[] countBits(int num) {
  2. int[] ret = new int[num + 1];
  3. for(int i = 1; i <= num; i++){
  4. ret[i] = ret[i&(i-1)] + 1;
  5. }
  6. return ret;
  7. }