Java backtracking solution, easy to understand


  • 0
    J

    I know lots people is doing it in bit way. This is just for fun and providing another idea. Feel free to comment on this. Thanks!

    public class Solution {
        public int min = Integer.MAX_VALUE;
        public int integerReplacement(int n) {
            integerReplacement((long)n, 0);
            return min;
        }
        public void integerReplacement(long n, int level) {
            if (n == 1) {
                min = Math.min(min, level);
                return;
            } else if (n < 1) {
                return;
            } else {
                if (n % 2 == 0) {
                    integerReplacement(n / 2, level + 1);
                } else {
                    integerReplacement(n + 1, level + 1);
                    integerReplacement(n - 1, level + 1);
                }
            }
        }
    }
    

Log in to reply
 

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