Class Solution
java.lang.Object
g2501_2600.s2571_minimum_operations_to_reduce_an_integer_to_0.Solution
2571 - Minimum Operations to Reduce an Integer to 0.<p>Medium</p>
<p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p>
<ul>
<li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations to make</em> <code>n</code> <em>equal to</em> <code>0</code>.</p>
<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>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> n = 39</p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong> We can do the following operations:</p>
<ul>
<li>
<p>Add 2<sup>0</sup> = 1 to n, so now n = 40.</p>
</li>
<li>
<p>Subtract 2<sup>3</sup> = 8 from n, so now n = 32.</p>
</li>
<li>
<p>Subtract 2<sup>5</sup> = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0.</p>
</li>
</ul>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> n = 54</p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong> We can do the following operations:</p>
<ul>
<li>
<p>Add 2<sup>1</sup> = 2 to n, so now n = 56.</p>
</li>
<li>
<p>Add 2<sup>3</sup> = 8 to n, so now n = 64.</p>
</li>
<li>
<p>Subtract 2<sup>6</sup> = 64 from n, so now n = 0. So the minimum number of operations is 3.</p>
</li>
</ul>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
minOperations
public int minOperations(int n)
-