Why does this recursive algorithm give an incorrect answer to input 2 147 483 647?

I am working on the following question:

Given a positive integer n, and you can perform the following operations:

  • If n is even, replace n with n / 2.
  • If n is odd, you can replace n with n + 1 or n - 1.

What is the minimum number of replacements needed for n to become 1?

Here is the code I came 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 entering 2147483647, my code incorrectly outputs 33 instead of the correct answer, 32. Why is my code giving the wrong answer here?

+4
source share
1 answer

, . , (2,147,483,647), , int, 32- , , , INT_MIN, 2,147,483,648. , , , , .

,

integerReplacement((n+1)/2)

(n + 1)/2 . , , .

- , n , (n + 1)/2 (n/2) + 1 ( ). , ,

integerReplacement((n / 2) + 1)

, .

+4

Source: https://habr.com/ru/post/1688745/


All Articles