I'm working on the following question:
Given a positive integer n and you can do operations as follow:
- If n is even, replace n with n/2.
- If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?
Here's the code I've come up with:
class Solution {
private:
unordered_map<int, long long> count_num;
public:
int integerReplacement(int n) {
count_num[1] = 0;count_num[2] = 1;count_num[3] = 2;
if(!count_num.count(n)){
if(n%2){
count_num[n] = min( integerReplacement((n-1)/2), integerReplacement((n+1)/2) )+2;
}else{
count_num[n] = integerReplacement(n/2) +1;
}
}
return(count_num[n]);
}
};
When the input is 2147483647, my code incorrectly outputs 33 instead of the correct answer, 32. Why is my code giving the wrong answer here?