題目:
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
給定一數,回傳其在二進位表示時,0改1,1改0後的值
ex:input:5(101)=>output:2(010)
這題使用位元運算
class Solution:
def findComplement(self, num: int) -> int:
i=1
while i<=num:
i=i<<1
return i-1^num
先設一數i為1,不斷行左移操作直到大於num
如5(101),i最後會跑到8(1000)
再回傳其-1和num行^操作的結果即可(111^101=010)
最後執行時間30ms(faster than 94.48%)
那我們下題見