3.1 KiB
3.1 KiB
[2749] Minimum Operations To Make The Integer Zero
題目資訊
- 難度: Medium
- 標籤: Bit Manipulation, Brainteaser, Enumeration
- 題目連結: LeetCode
- 練習日期: 2025-09-05
題目描述
You are given two integers num1
and num2
.
In one operation, you can choose integer i in the range [0, 60]
and subtract 2^i + num2
from num1
.
Return the integer denoting the minimum number of operations needed to make num1
equal to 0
.
If it is impossible to make num1
equal to 0
, return -1
.
解題思路
初步分析
- 這題主要考察什麼概念?
- 位元操作 (Bit Manipulation):需要理解二進制表示和位元運算
- 數學建模:將實際問題轉換為數學等式
- 枚舉 (Enumeration):嘗試不同的操作次數 k
- 約束條件判斷:理解多個限制條件的邏輯關係
- 有什麼關鍵限制條件?
- target ≥ 0
- bitCount(target) ≤ k
- k ≤ target
- 預期時間/空間複雜度?
- 時間複雜度:O(60 × log(target)) ≈ O(1)
- 空間複雜度:O(1)
解法概述
- 解法:
- 思路:
- 目標:讓 num1 變成 0
- 每次操作:num1 = num1 - (2^i + num2)
- k 次操作後:num1 - k*num2 - (2^i1 + 2^i2 + ... + 2^ik) = 0
- 重新整理:target = num1 - k*num2 = 2^i1 + 2^i2 + ... + 2^ik
- 時間複雜度:O(1)
- 空間複雜度:O(1)
- 思路:
測試案例
範例輸入輸出
Input: num1 = 3, num2 = -2
Output: 3
Explanation:
We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 22 + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 22 + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 20 + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
邊界情況
1 <= num1 <= 10^9
-10^9 <= num2 <= 10^9
學習筆記
今天學到什麼?
- 二位元的操作寫法
遇到的困難
- 二位元的操作
- 方法一: 逐位檢查法
- 程式碼:
count += (int)(n & 1); n >>= 1;
- 運作原理:
- n & 1:檢查最右邊的位元是否為 1
- count += (int)(n & 1):如果是 1 就加到計數器
- n >>= 1:把 n 右移一位(去掉已檢查的位元)
- 重複直到 n 變成 0
- 方法二: 移除最右邊 1
- 程式碼:
count++; n &= n - 1;
- 運作原理:
- n - 1:讓最右邊的 1 變成 0,其右邊的 0 都變成 1
- n & (n - 1):神奇地移除了最右邊的 1
- count++:每移除一個 1,計數器就加 1
- 重複直到 n 變成 0
- 方法一: 逐位檢查法
改善方向
相關題目
總結:
- 學習二位元的使用技巧