Java 5 lines 4ms recursive math solution


  • 0
    L
    public class Solution {
        public int integerReplacement(int n) {
            if(n==1) return 0;
            if(n==3) return 2;
            if(n==2147483647) return integerReplacement(n/2+1)+2;
            if(n%2==0) return integerReplacement(n/2)+1;
            else return n%4==1?integerReplacement(n-1)+1:integerReplacement(n+1)+1;
        }
    }
    

    Any suggestion on how to better deal with overflow?


Log in to reply
 

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