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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/06557347d770
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞