主要内容:
- Leetcode题目,类型[Bit Manipulation]
- Java语言实现
题目
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits),
and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits),
and its complement is 0. So you need to output 0.
实现
代码实现:git地址,可以关注我github地址,持续更新Leetcode代码实现。
题目的意思是,求一个数二进制表示的补数。不难看出,与输入值位数相同且bit值均为1的数与输入值进行异或后,会得到结果。例如example 1中101对应的比较数是111,111与101异或后得到010即结果。
第一种
/**
* 假设num二进制表示为n位,则循环结束后comp是10...0(n-1位0),
* 减1就得到和num位数相同且bit值都是1的数
*/
public int findComplement(int num) {
int temp = num,comp = 1;
while(temp != 0){
temp >>= 1;
comp <<= 1;
}
return (comp - 1) ^ num;
}