Python實現 數字的補數 的兩種方法

2021-08-30 04:22:32 字數 1497 閱讀 3942

給定乙個整數,返回它的補數.補數策略針對整數的二進位制位

注意:

給定的整數最大為32位

假設二進位制不包含前導0

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.

def

findcomplement

(self, num)

:"""

:type num: int

:rtype: int

"""newbit =

""for i in

bin(num)[2

:]: newbit +=

"1"if i ==

"0"else

"0"return

int(

"0b"

+ newbit,

2)

return

int(

"".join(

map(

lambda ch:

'1'if ch==

'0'else

'0',

bin(num)[2

:]))

,2)

def

findcomplement

(self, num)

:"""

:type num: int

:rtype: int

"""x = math.floor(math.log(num,2)

)+1return

int(

2**x)

- num -

1

def

findcomplement

(self, num)

:"""

:type num: int

:rtype: int

"""s =

1while s<=num:

s<<=1

return

(s-1

)^num

演算法題來自:

476數字的補數

題目點我 給定乙個正整數,輸出它的補數。補數是對該數的二進位制表示取反。注意 給定的整數保證在32位帶符號整數的範圍內。你可以假定二進位制數不包含前導零位。示例 1 輸入 5 輸出 2 解釋 5的二進位制表示為101 沒有前導零位 其補數為010。所以你需要輸出2。示例 2 輸入 1 輸出 0 解釋...

476 數字的補數

題目 給定乙個正整數,輸出它的補數。補數是對該數的二進位制表示取反。注意 給定的整數保證在32位帶符號整數的範圍內。你可以假定二進位制數不包含前導零位 示例 1 輸入 5輸出 2解釋 5的二進位制表示為101 沒有前導零位 其補數為010。所以你需要輸出2。示例 2 輸入 1輸出 0解釋 1的二進位...

476 數字的補數

給定乙個正整數,輸出它的補數。補數是對該數的二進位制表示取反。注意 給定的整數保證在32位帶符號整數的範圍內。你可以假定二進位制數不包含前導零位。示例 1 輸入 5 輸出 2 解釋 5的二進位制表示為101 沒有前導零位 其補數為010。所以你需要輸出2。示例 2 輸入 1 輸出 0 解釋 1的二進...