-
发表于 2024.07.26
-
可使用贪心法解决:从低位到高位逐位比较
a
、b
和c
的对应位,如果c
的对应位为1
,则a
和b
的对应位至少有一个为1
,否则需要翻转1
次即可。如果c
的对应位为0
,则a
和b
的对应位需要全为0
,此时翻转次数为a的对应位 + b的对应位
。因此,只需要逐位比较并累加需要翻转的次数即可。class Solution: def minFlips(self, a: int, b: int, c: int) -> int: ans = 0 while a or b or c: has_one = c & 1 cur_res = (a & 1) | (b & 1) if has_one != cur_res: if has_one: ans += 1 else: ans += (a & 1) + (b & 1) a >>= 1 b >>= 1 c >>= 1 return ans
- LC 题目链接
-