7ms java AC recursion. One question asked.


  • 0
    S

    I think when n == Integer.MAX_VALUE, the official answer is wrong. The given answer is 32 while the answer of Integer.MAX_VALUE - 1 is also 32. So at least we have to move max value to max value - 1 so the answer should be 33. Can anyone explain this to me?

    public int integerReplacement(int n) {
            if(n <= 3) return n - 1;
            if(n == Integer.MAX_VALUE) return 32;
            int count = 0;
            while(n > 1){
                if(n % 2 == 0){
                    n = n / 2;
                    count++;
                }else{
                    int less = integerReplacement(n - 1);
                    int more = integerReplacement(n + 1);
                    if(less > more){
                        count += more + 1;
                        break;
                    }else{
                        count += less + 1;
                        break;
                    }
                }
            }
            return count;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.