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:
Example 2:
解法1:
观察可以发现,可以用XOR来flip每一位的bit, 而mark数是从第一个set bit开始所有位都为1的数字。
怎么判断最高的set bit是哪一个呢?可以用log2函数,最高位的1的位置一定是log2(num), 那么为了得到所有都是1的一个数,可以先左移log2(num) + 1, 然后把所得的数字-1即可。
C++
Java
解法2:一位一位的转换
Java