Leetcode 150 Bit Manipulation解題思路
Leetcode 150 Bit Manipulation解題思路¶
這種題型主要考的是如何去handle 把十進位數字做二進位的相關運算
首先基礎要帶到的,以python為例
8>>1 #會先把8轉換為二進制的1000,>>表示把這些bit右移i單位,左邊補0,因此成為01008<<1 #會先把8轉換為二進制的1000,<<表示把這些bit左移i單位,右邊補0,因此成為1000012&4 #& AND的運算為,必須要都為1才會是1,其餘為0,因此 1100&0100 -> 0100 為412&4 #| or的運算為,必須要都為0才會是0,其餘為1,因此 1100|0100 -> 1100 為1212^4 #^ xor的運算為,如果兩個數字一樣為0,不同為1,因此 1100^0100 -> 1000為8
以上是基本概念,基本題型有
考兩個數字的相加或相減,基本概念為如果兩個相同位數都為1,該數字變為0且進為+1,持續走訪
def addBinary(self, a: str, b: str) -> str: res = [] _a, _b, carry = len(a)-1, len(b)-1, 0 while _a>=0 or _b>=0 or carry: if _a>=0: carry+=int(a[_a]) _a-=1 if _b>=0: carry+=int(b[_b]) _b-=1 res.append(str(carry%2)) print(str(carry%2)) carry = carry//2 return ''.join(reversed(res))
考換位符號,例如兩個數字間數字做AND運算,或是去反轉一個32bit的數字
def reverseBits(self, n: int) -> int: res = 0 for i in range(32): res<<=1 last = n&1 #keep smallest element n>>=1 res = res|last return res#基本上,一開始先把res指定為0#走訪32次,一開始先res左移一位,#接下來用last去紀錄1跟當下N的AND值,因為是跟1所以只會有最右邊被留下#接下來先將n左移一位#最後res需要去跟last去做OR比對,因為last只會是0或1,不會影響到左邊第二位之後的res中其他數值,如此以往就可以完成反轉
還有透過XOR特性可以去檢查一個list中是否有唯一的值(但重複的值須為雙數),這樣可以透過XOR相同值會歸零的特性,保留唯一值
#最切中題目要求的解法,走訪所有list去做XOR,linear time and spacexor = 0for num in nums: xor ^= num#當然也可以透過hash map的模式去找,但空間複雜度較高 O(n) def singleNumber(self, nums: List[int]) -> int: res = {} for i in nums: if i in res.keys(): del res[i] else: res[i]=1 return list(res.keys())[0]
也是一種可以有很多變化型的類別
Comments
Loading comments…
Leave a Comment