|
| 1 | +<h2><a href="https://leetcode.com/problems/minimum-bit-flips-to-convert-number">2220. Minimum Bit Flips to Convert Number</a></h2><h3>Easy</h3><hr><p>A <strong>bit flip</strong> of a number <code>x</code> is choosing a bit in the binary representation of <code>x</code> and <strong>flipping</strong> it from either <code>0</code> to <code>1</code> or <code>1</code> to <code>0</code>.</p> |
| 2 | + |
| 3 | +<ul> |
| 4 | + <li>For example, for <code>x = 7</code>, the binary representation is <code>111</code> and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get <code>110</code>, flip the second bit from the right to get <code>101</code>, flip the fifth bit from the right (a leading zero) to get <code>10111</code>, etc.</li> |
| 5 | +</ul> |
| 6 | + |
| 7 | +<p>Given two integers <code>start</code> and <code>goal</code>, return<em> the <strong>minimum</strong> number of <strong>bit flips</strong> to convert </em><code>start</code><em> to </em><code>goal</code>.</p> |
| 8 | + |
| 9 | +<p> </p> |
| 10 | +<p><strong class="example">Example 1:</strong></p> |
| 11 | + |
| 12 | +<pre> |
| 13 | +<strong>Input:</strong> start = 10, goal = 7 |
| 14 | +<strong>Output:</strong> 3 |
| 15 | +<strong>Explanation:</strong> The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps: |
| 16 | +- Flip the first bit from the right: 101<u>0</u> -> 101<u>1</u>. |
| 17 | +- Flip the third bit from the right: 1<u>0</u>11 -> 1<u>1</u>11. |
| 18 | +- Flip the fourth bit from the right: <u>1</u>111 -> <u>0</u>111. |
| 19 | +It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.</pre> |
| 20 | + |
| 21 | +<p><strong class="example">Example 2:</strong></p> |
| 22 | + |
| 23 | +<pre> |
| 24 | +<strong>Input:</strong> start = 3, goal = 4 |
| 25 | +<strong>Output:</strong> 3 |
| 26 | +<strong>Explanation:</strong> The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps: |
| 27 | +- Flip the first bit from the right: 01<u>1</u> -> 01<u>0</u>. |
| 28 | +- Flip the second bit from the right: 0<u>1</u>0 -> 0<u>0</u>0. |
| 29 | +- Flip the third bit from the right: <u>0</u>00 -> <u>1</u>00. |
| 30 | +It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3. |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p> </p> |
| 34 | +<p><strong>Constraints:</strong></p> |
| 35 | + |
| 36 | +<ul> |
| 37 | + <li><code>0 <= start, goal <= 10<sup>9</sup></code></li> |
| 38 | +</ul> |
0 commit comments