Skip to content

397. Integer Replacement

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int integerReplacement(long n) {
    int ans = 0;

    for (; n > 1; ++ans)
      if (n % 2 == 0)  // `n` ends in 0.
        n >>= 1;
      else if (n == 3 || (n >> 1 & 1) == 0)  // `n` = 3 or ends in 0b01.
        --n;
      else  // `n` ends in 0b11.
        ++n;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int integerReplacement(long n) {
    int ans = 0;

    for (; n > 1; ++ans)
      if (n % 2 == 0) // `n` ends in 0.
        n >>= 1;
      else if (n == 3 || (n >> 1 & 1) == 0) // `n` = 3 or ends in 0b01.
        --n;
      else // `n` ends in 0b11.
        ++n;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def integerReplacement(self, n: int) -> int:
    ans = 0

    while n > 1:
      if n % 2 == 0:  # `n` ends in 0.
        n >>= 1
      elif n == 3 or (n >> 1 & 1) == 0:  # `n` = 3 or ends in 0b01.
        n -= 1
      else:  # `n` ends in 0b11.
        n += 1
      ans += 1

    return ans