Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-09-11 08:37:44
https://leetcode.com/problems/minimum-bit-flips-to-convert-number
2220. Minimum Bit Flips to Convert Number
位元翻轉 (bit flip) 是數的二進位表示中 將其中一個位元從 0 轉 1 或 1 轉 0
給一個 start 求位元翻轉成 goal 最少要花的次數
Example 1:
Input: start = 10, goal = 7
Output: 3
Explanation: 10 跟 7 分別是 1010 和 0111 要翻轉的有 1, 3, 4 個位子 答案 3
Example 2:
Input: start = 3, goal = 4
Output: 3
Explanation: 3 跟 4 分別是 011 和 100 三個位子都要翻轉 答案 3
思路:照做
※ 引述《DJYOMIYAHINA (通通打死)》之銘言:
: 早早早早早
: 一二三四五
: def minBitFlips(self, start: int, goal: int) -> int:
: ans = 0
: x = start^goal
: while x>0:
: ans += (x&1)
: x = x >> 1
: return ans
Python Code:
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
return bin(start ^ goal).count('1')
好短
作者: sustainer123 (caster)   2024-09-11 08:38:00
早早早
作者: oin1104 (是oin的說)   2024-09-11 08:38:00
早早早
作者: JerryChungYC (JerryChung)   2024-09-11 08:38:00

Links booklink

Contact Us: admin [ a t ] ucptt.com