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.
分析:
就是求一个数的反码,还保证了是32bit的数
思路:
这里介绍两种方法:
- 用Python内置的bin()函数获得Num的二进制表示形式,然后’0’ ‘1’互换即可
- 101 -> 010, 我们可以发现其实就是找0的位置,想到用全1的数来进行异或操作, 即101 ^ 111 = 010
1 | # 字符串转换 |