why my code is error when Input is 100000000


  • 0

    My mind is that when number is 1, 11 or 111, first -1 always can get the smallest result. when the count of tail 1 is more than 3, we +1 and then /2 is the better way.
    so my code is below:

    public int integerReplacement(int n) {
            int count = 0;
            while (n != 1) {
                BitTool.showBinary(n);
                if (n % 2 == 0) {
                    n /= 2;
                } else if ((n & 7) == 7) {
                    n += 1;
                } else {
                    n -= 1;
                }
                count++;
            }
            return count;
        }
    

    but when input is int n = 100_000_000, my answer is 32 and the right answer is 31, I do not know why?


Log in to reply
 

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