整数替换

给定一个正整数 n,你可以做如下操作:

1. 如果 n 是偶数,则用 n / 2替换 n。
2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。
n 变为 1 所需的最小替换次数是多少?

function integerReplacement(n) {
    let times = 0
    while(true){
        if(n == 1){
            return times
        }else{
            if(n % 2 == 0){
                n /= 2
            }else{
                if(((n - 1) / 2) % 2 == 0 || (n - 1) == 2){
                    n -= 1
                }else{
                    n += 1
                }
            }
            ++num
        }
    }
}  

Leecode提交通过

原文地址:https://www.cnblogs.com/zhenjianyu/p/13466777.html