Leetcode 476 Number Complement

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的数

思路:
这里介绍两种方法:

  1. 用Python内置的bin()函数获得Num的二进制表示形式,然后’0’ ‘1’互换即可
  2. 101 -> 010, 我们可以发现其实就是找0的位置,想到用全1的数来进行异或操作, 即101 ^ 111 = 010
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 字符串转换
def findComplement(num):
s = bin(nums)
res = ''
for e in s[2:]:
res += str(1-int(e))
return int(res,2)

# 异或操作
def findComplement(num):
return num ^ ((1<<num.bit_length())-1)

149 / 149 test cases passed.
dfficulty: easy
Runtime: 35 ms