476.Number Complement
Description:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.Note:
1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
2. 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.
以上是题目,因为例子解释得很清楚就不翻译题目内容了。
第一眼看这题,就想咋这么简单,取反操作不就完了,然后就gg了…
错误代码:
public class Solution {
public int findComplement(int num) {
return ~num;
}
}
错误结果:
呵呵,大兄弟,你好像忘了int类型在java里是存储为补码形式的32位数了。
那就赶紧重新整理思路,其实取反操作是没啥问题,问题是要进行怎样的操作才能保证前导零不变的同时对其取反,容易想到以下两个与操作:
1. 输入数取反前的前导零位在取反后与“0”进行按位与操作;
2. 输入数取反前最左边的最高一位及其之后的位在取反后与“1”进行按位与操作;
即我们需要得到一个数,这个数取输入数的二进制形式最左边的最高一位且高位后面全部补“1”。
就得到如下代码:
public class Solution {
public int findComplement(int num) {
return ~num&((Integer.highestOneBit(num)<<1)-1);
}
}
结果正确。
PS: highestOneBit(i):这个函数的作用是取 i 这个数的二进制形式最左边的最高一位且高位后面全部补零,最后返回int型的结果。
再进一步想,输入数最左边的最高位肯定是“1”,取反后为“0”,那进行与操作肯定是“0”,所以在这里我们可以把左移运算省略,即:
public class Solution {
public int findComplement(int num) {
return ~num&(Integer.highestOneBit(num)-1);
}
}
完成。
还是一行代码的事儿……主要还是java的基础函数吧。