LeetCode476-数字的补数

题目链接

英文链接:https://leetcode.com/problems/number-complement/

中文链接:https://leetcode-cn.com/problems/number-complement/

题目详述

给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。

注意:

  1. 给定的整数保证在32位带符号整数的范围内。
  2. 你可以假定二进制数不包含前导零位。

示例 1:

1
2
3
输入: 5
输出: 2
解释: 5的二进制表示为101(没有前导零位),其补数为010。所以你需要输出2。

示例 2:

1
2
3
输入: 1
输出: 0
解释: 1的二进制表示为1(没有前导零位),其补数为0。所以你需要输出0。

题目详解

方法一:逐位取反相加。

1
2
3
4
5
6
7
8
9
10
11
12
public class LeetCode_00476 {

public int findComplement(int num) {
int res = 0;
int t = 0;
while (num != 0) {
res |= ((num & 1) == 1 ? 0 : 1) << t++;
num >>= 1;
}
return res;
}
}

方法二:得到取反后与最后的几位数的掩码进行 & 运算,或者直接与掩码进行异或也能达到取反的效果。

1
2
3
4
5
6
7
public class LeetCode_00476 {

public int findComplement(int num) {
// return ~num & ((Integer.highestOneBit(num) << 1) - 1);
return num ^ ((Integer.highestOneBit(num) << 1) - 1);
}
}