https://leetcode.com/problems/integer-replacement/

// 除了首位的1,其他的1需要2次操作,0需要1次操作。
// 所以尽量把1变成0
// 所以,3直接得出结果2,
// 其他的,01->-1,11->+1

public class Solution {
    public int integerReplacement(int inn) {
        long n = inn;
        if (n <= 3) {
            return (int)n-1;
        }
        
        int step = 0;
        while (n > 3) {
            // 注意下面的括号,必须有
            if ((n & 1) == 0) {
                n >>= 1;
            }
            else if ((n & 2) == 2) {
                n += 1;
            }
            else {
                n -= 1;
            }
            step++;
        }
        return step + (int)n - 1;
    }
}

 

相关文章:

  • 2021-08-15
  • 2021-08-06
  • 2021-08-26
  • 2021-05-19
  • 2022-12-23
  • 2021-11-03
  • 2021-05-25
  • 2021-12-14
猜你喜欢
  • 2021-12-20
  • 2021-06-21
  • 2022-12-23
  • 2021-10-23
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案