|
| 1 | +<h2><a href="https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0">2710. Minimum Operations to Reduce an Integer to 0</a></h2><h3>Medium</h3><hr><p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p> |
| 2 | + |
| 3 | +<ul> |
| 4 | + <li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li> |
| 5 | +</ul> |
| 6 | + |
| 7 | +<p>Return <em>the <strong>minimum</strong> number of operations to make </em><code>n</code><em> equal to </em><code>0</code>.</p> |
| 8 | + |
| 9 | +<p>A number <code>x</code> is power of <code>2</code> if <code>x == 2<sup>i</sup></code> where <code>i >= 0</code><em>.</em></p> |
| 10 | + |
| 11 | +<p> </p> |
| 12 | +<p><strong class="example">Example 1:</strong></p> |
| 13 | + |
| 14 | +<pre> |
| 15 | +<strong>Input:</strong> n = 39 |
| 16 | +<strong>Output:</strong> 3 |
| 17 | +<strong>Explanation:</strong> We can do the following operations: |
| 18 | +- Add 2<sup>0</sup> = 1 to n, so now n = 40. |
| 19 | +- Subtract 2<sup>3</sup> = 8 from n, so now n = 32. |
| 20 | +- Subtract 2<sup>5</sup> = 32 from n, so now n = 0. |
| 21 | +It can be shown that 3 is the minimum number of operations we need to make n equal to 0. |
| 22 | +</pre> |
| 23 | + |
| 24 | +<p><strong class="example">Example 2:</strong></p> |
| 25 | + |
| 26 | +<pre> |
| 27 | +<strong>Input:</strong> n = 54 |
| 28 | +<strong>Output:</strong> 3 |
| 29 | +<strong>Explanation:</strong> We can do the following operations: |
| 30 | +- Add 2<sup>1</sup> = 2 to n, so now n = 56. |
| 31 | +- Add 2<sup>3</sup> = 8 to n, so now n = 64. |
| 32 | +- Subtract 2<sup>6</sup> = 64 from n, so now n = 0. |
| 33 | +So the minimum number of operations is 3. |
| 34 | +</pre> |
| 35 | + |
| 36 | +<p> </p> |
| 37 | +<p><strong>Constraints:</strong></p> |
| 38 | + |
| 39 | +<ul> |
| 40 | + <li><code>1 <= n <= 10<sup>5</sup></code></li> |
| 41 | +</ul> |
0 commit comments