ให้จำนวนเต็มบวก n ทำการดำเนินการ:
- ถ้า
nคู่ →n = n/2 - ถ้า
nคี่ →n = n+1หรือn = n-1
n = 1
ตัวอย่าง: 7 → 4 (7→8→4→2→1 หรือ 7→6→3→2→1)
ขั้นตอนการแก้ปัญหา (Greedy + Bit Manipulation)
ret = 0, ใช้long longกัน overflow- วนจน
n > 1:- ถ้า
nคู่ →n >>= 1 - ถ้า
nคี่:- ถ้า
n == 3หรือ(n >> 1) & 1 == 0(บิตถัดไปเป็น 0) →n-- - มิฉะนั้น →
n++
- ถ้า
ret++
- ถ้า
- คืน
ret
เหตุผล: ต้องการให้ได้ 0 ติดกันมากที่สุดเพื่อหาร 2 เร็วขึ้น ยกเว้น n=3 ที่ -1 เร็วกว่า
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
typedef long long lli;
class Solution {
public:
int integerReplacement(int x) {
int ret = 0;
lli n = x;
while (n > 1) {
if (n % 2 == 0) n >>= 1;
else if (n & 1) {
if (n == 3 || ((n >> 1) & 1) == 0) n--;
else n++;
}
ret++;
}
return ret;
}
};
int main() {
Solution ob;
cout << ob.integerReplacement(7);
}
Input
7
Output
4