Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
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.
我能想到的直观思路,就是在二进制转十进制的时候将各位余数数值取反,然后再转换为十进制。
但是知道我看到了最优解:Java 1 line bit manipulation solution(仅仅一句话代码)
我们首先要理解位运算:
说明:
非:
非运算符用符号“~”表示,其运算规律如下:
如果位为0,结果是1,如果位为1,结果是0,也就是每位都取反了。
在上述代码中:结果是 10 —> 01
与:
与运算符用符号“&”表示,其使用规律如下:
两个操作数中位都为1,结果才为1,否则结果为0
在上述代码中:结果是 100101001&100101000—>100101000
然后我们总结一下一句话代码:
LeetCode_Easy_471:Number Complement
原文:http://www.cnblogs.com/MrSaver/p/6711111.html