Simple Java with no edge cases (checking for max val)


  • 0
    D

    We can avoid checking for maximum value in our while loop. We want to maximize the number of even digits we hit, so we look at an odd number's grandson (i.e. either (n+1)/2 or (n -1)/2 is even since they're consecutive numbers). We can rewrite this logic as n/2 since integers round down in java (if n/2 is even, then (n-1)/2 will also be even). If n/2 is not even, then we know that we need to take the higher one. We do this by calculating n/2 + 1 and incrementing count by 2. This way, we take care of the case for n = 1, n = 2, n= 3, and n = Integer.MAX_VALUE without pesky if/else edge catches.

    public class Solution {
        public int integerReplacement(int n) {
            int count = 0;
            while(n != 1) {
                if(n % 2 == 0) {
                    n = n/2;
                    count++;
                }
                else {
                    if(n/2 % 2 == 0 || n == 3) {
                        n = n/2;
                        count += 2;
                    }
                    else {
                        n = n/2 + 1;
                        count += 2;
                    }
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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