|
| 1 | +<h2><a href="https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one">1404. Number of Steps to Reduce a Number in Binary Representation to One</a></h2><h3>Medium</h3><hr><p>Given the binary representation of an integer as a string <code>s</code>, return <em>the number of steps to reduce it to </em><code>1</code><em> under the following rules</em>:</p> |
| 2 | + |
| 3 | +<ul> |
| 4 | + <li> |
| 5 | + <p>If the current number is even, you have to divide it by <code>2</code>.</p> |
| 6 | + </li> |
| 7 | + <li> |
| 8 | + <p>If the current number is odd, you have to add <code>1</code> to it.</p> |
| 9 | + </li> |
| 10 | +</ul> |
| 11 | + |
| 12 | +<p>It is guaranteed that you can always reach one for all test cases.</p> |
| 13 | + |
| 14 | +<p> </p> |
| 15 | +<p><strong class="example">Example 1:</strong></p> |
| 16 | + |
| 17 | +<pre> |
| 18 | +<strong>Input:</strong> s = "1101" |
| 19 | +<strong>Output:</strong> 6 |
| 20 | +<strong>Explanation:</strong> "1101" corressponds to number 13 in their decimal representation. |
| 21 | +Step 1) 13 is odd, add 1 and obtain 14. |
| 22 | +Step 2) 14 is even, divide by 2 and obtain 7. |
| 23 | +Step 3) 7 is odd, add 1 and obtain 8. |
| 24 | +Step 4) 8 is even, divide by 2 and obtain 4. |
| 25 | +Step 5) 4 is even, divide by 2 and obtain 2. |
| 26 | +Step 6) 2 is even, divide by 2 and obtain 1. |
| 27 | +</pre> |
| 28 | + |
| 29 | +<p><strong class="example">Example 2:</strong></p> |
| 30 | + |
| 31 | +<pre> |
| 32 | +<strong>Input:</strong> s = "10" |
| 33 | +<strong>Output:</strong> 1 |
| 34 | +<strong>Explanation:</strong> "10" corressponds to number 2 in their decimal representation. |
| 35 | +Step 1) 2 is even, divide by 2 and obtain 1. |
| 36 | +</pre> |
| 37 | + |
| 38 | +<p><strong class="example">Example 3:</strong></p> |
| 39 | + |
| 40 | +<pre> |
| 41 | +<strong>Input:</strong> s = "1" |
| 42 | +<strong>Output:</strong> 0 |
| 43 | +</pre> |
| 44 | + |
| 45 | +<p> </p> |
| 46 | +<p><strong>Constraints:</strong></p> |
| 47 | + |
| 48 | +<ul> |
| 49 | + <li><code>1 <= s.length <= 500</code></li> |
| 50 | + <li><code>s</code> consists of characters '0' or '1'</li> |
| 51 | + <li><code>s[0] == '1'</code></li> |
| 52 | +</ul> |
0 commit comments