Leetcode - Integer Replacement

My code:

public class Solution {
    public int integerReplacement(int n) {
        if (n == Integer.MAX_VALUE) {
            return 32;
        }
        
        int cnt = 0;
        while (n != 1) {
            if (n % 2 == 0) {
                n /= 2;
            }
            else if ((n + 1) % 4 == 0 && n != 3) {
                n++;
            }
            else {
                n--;
            }
            cnt++;
        }
        
        return cnt;
    }
}

reference:
https://discuss.leetcode.com/topic/58425/java-12-line-4-5-ms-iterative-solution-with-explanations-no-other-data-structures

这个解释讲的挺不错的

Anyway, Good luck, Richardo! -- 10/14/2016

你可能感兴趣的:(Leetcode - Integer Replacement)