397. Integer Replacement
Given a positive integer n, you can apply one of the following operations:
- If n is even, replace n with n / 2.
- If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: int integerReplacement(int n) { map<long, int> v; queue<long> q; v[n] = 0; q.push(n); while(!v.count(1)) { long num = q.front(); q.pop(); if(num & 1) { if(!v.count(num + 1)) { v[num + 1] = v[num] + 1; q.push(num + 1); }
if(!v.count(num - 1)) { v[num - 1] = v[num] + 1; q.push(num - 1); } } else if(!v.count(num>>1)) { v[num >> 1] = v[num] + 1; q.push(num >> 1); } }
return v[1]; } };
|