classSolution(object): defminFlips(self, a, b, c): """ :type a: int :type b: int :type c: int :rtype: int """ x, y, z = bin(a)[2:], bin(b)[2:], bin(c)[2:] n = max(len(x), len(y), len(z))
# 二進位且長度不同時,短者前面補 0 for i inrange(n-len(x)): x = "0" + x for i inrange(n-len(y)): y = "0" + y for i inrange(n-len(z)): z = "0" + z
cnt = 0 for i inrange(n): o, p, q = int(x[i]), int(y[i]), int(z[i]) if q == o | p: continue else: if q == 0: cnt += o+p else: cnt += (o|p)^1 return cnt
classSolution(object): defminFlips(self, a, b, c): """ :type a: int :type b: int :type c: int :rtype: int """ x, y, z, cnt = bin(a)[2:], bin(b)[2:], bin(c)[2:], 0 n = max(len(x), len(y), len(z)) dic = {'010':1, '100':1, '001':1, '110':2}
o, p, q = x.zfill(n), y.zfill(n), z.zfill(n) for i inrange(n): cnt += dic.get(o[i]+p[i]+q[i], 0) return cnt
Complexity
Time Complexity: O(n)
n 個位置的話,每位位置走過一次操作即 n 次
Space Complexity: O(1)
基本上無使用到額外空間
模擬
Bit Manipulation
相同的方式,只是取位以 Bit Manipulation 方式操作,注意 Least Significant Bit (LSB)、最右一位數字的取得方式為 (x & 1)
程式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defminFlips(self, a, b, c): """ :type a: int :type b: int :type c: int :rtype: int """ cnt = 0 for i inrange(32): if (a&1) | (b&1) != (c&1): if (c&1) == 1: cnt += 1 else: cnt += (a&1) + (b&1) a, b, c = a>>1, b>>1, c>>1 return cnt
Complexity
Time Complexity: O(n)
n 個位置的話,每位位置走過一次操作即 n 次
Space Complexity: O(1)
基本上無使用到額外空間
一行解
from hrxue;一樣是同樣概念;先確認 a|b 與 c 的差異有多少,做為至少 1 個要翻的計數,再檢查有無 1 and 1 -> 0 的狀況發生,即是要再翻轉一次
程式
1 2 3 4 5 6 7 8 9
classSolution(object): defminFlips(self, a, b, c): """ :type a: int :type b: int :type c: int :rtype: int """ returnbin((a | b) ^ c).count('1') + bin((a & b) & ~c).count('1')