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 & 1) == 0)  // ends w/ 0
        n >>= 1;
      else if (n == 3 || ((n >> 1) & 1) == 0)  // n = 3 or ends w/ 01
        --n;
      else  // ends w/ 11
        ++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 & 1) == 0) // ends w/ 0
        n >>= 1;
      else if (n == 3 || ((n >> 1) & 1) == 0) // n = 3 or ends w/ 01
        --n;
      else // ends w/ 11
        ++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 & 1) == 0:
        n >>= 1
      elif n == 3 or ((n >> 1) & 1) == 0:
        n -= 1
      else:
        n += 1
      ans += 1

    return ans
Back to top