题目:
Every non-negative integer N
has a binary representation. For example, 5
can be represented as "101"
in binary, 11
as "1011"
in binary, and so on. Note that except for N = 0
, there are no leading zeroes in any binary representation.
The complement of a binary representation is the number in binary you get when changing every 1
to a 0
and 0
to a 1
. For example, the complement of "101"
in binary is "010"
in binary.
For a given number N
in base-10, return the complement of it's binary representation as a base-10 integer.
也就是说将一个非负整数的二进制表示(没有前导0)中的1变为0,0变为1,然后返回其表示的十进制数
Example 1:
Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
解题思路一:
使用循环不断除2和模2求得整数N的每一位二进制表示,如果某位上的二进制表示为0,则就乘2的n次方(n初始为0,每次跟着循环加1)以达到该数每位取反的效果。
代码:
class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
mul = 1
sum = 0
while N:
mod = N % 2
if(not mod):
sum += mul
mul <<= 1
N = int(N/2)
return sum
解题思路二:
将一个非负整数的二进制表示(没有前导0)中的1变为0,0变为1,其实也就是将N与当前N表示的二进制数的最大值异或。
例如 5,5的二进制表示是101,当前二进制数的最大值就是每位上都为1的数111,101与111异或得到的就是010(2)
那怎么直到当前的二进制位数的最大值是多少呢?可以用一个循环解决,将一个数m初始化为1,然后将N不断右移,直到结果为0,在右移的过程中,每右移一位,就将m加上2的n次方(即就是二进制的每一位都是1),这样循环结束便可得到最大值的十进制数。
代码:
class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
m = 0
part = 1
n = N
while n:
m += part
n >>=1 # 每次右移一位,直到为0,就可以直到当前的二进制表示有多少位
part <<=1 # 每个二进制位都为1,实际上就是乘以2的n次方
return N^m