Class Solution

java.lang.Object
g0301_0400.s0397_integer_replacement.Solution

public class Solution extends Object
397 - Integer Replacement.<p>Medium</p> <p>Given a positive integer <code>n</code>, you can apply one of the following operations:</p> <ol> <li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li> <li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li> </ol> <p>Return <em>the minimum number of operations needed for <code>n</code> to become <code>1</code></em>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> n = 8</p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong> 8 -> 4 -> 2 -> 1</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> n = 7</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong> 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> n = 4</p> <p><strong>Output:</strong> 2</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= n <= 2<sup>31</sup> - 1</code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • integerReplacement

      public int integerReplacement(int n)