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.
分析:
给定一个正整数,按位取反, 比如题目中给出的5,二进制为101,那么取反就是010, 010对应的十进制数是2.
实现这个功能的话,按位取反,很容易想到异或操作符^, 将原数比如101与111进行抑或操作,那么所得结果就是010.也就是我们需要的。
代码实现:
function complement(number) { var mask = 1; var temp = number; while( temp > 0) { temp = temp >> 1; mask = mask << 1; } return number ^ (mask-1); } complement(1);
这里 mask-1是为了取111...值。