Number of Steps to Reduce a Number in Binary Representation to One Problem
Description
LeetCode Problem 1404.
Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
- If the current number is even, you have to divide it by
2. - If the current number is odd, you have to add
1to it.
It is guaranteed that you can always reach one for all test cases.
Example 1:
Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.
Example 2:
Input: s = "10"
Output: 1
Explanation: "10" corresponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.
Example 3:
Input: s = "1"
Output: 0
Constraints:
1 <= s.length <= 500sconsists of characters '0' or '1's[0] == '1'
Solution
Approach: Scan the Bits from the Right with a Carry
The number can have 500 bits, far too many for a built-in integer type, so we simulate on the string. Look at the bits from the lowest one up:
- If the lowest bit is
0, the number is even: divide by 2, which removes that bit. 1 step. - If the lowest bit is
1, the number is odd: add 1, which turns that bit into0and carries a1into the next bit, then divide by 2. 2 steps.
The add-one only touches the bits above through the carry, so instead of rewriting the string we keep a carry (0 or 1) and add it to each bit as we reach it. The current bit is s[i] + carry:
1: odd, 2 steps, and the carry becomes (or stays) 1.0or2(a1plus a carry, which becomes0with the carry passed on): even, 1 step, and the carry does not change.
Stop before the leading bit (index 0), which is always 1. If there is no carry, the number is now 1 and we are done. If there is a carry, the leading bit became 10, which takes one more division. So the answer is steps + carry.
Example 1, "1101" (13): bit 1 costs 2 steps (carry 1), bit 0 + 1 = 1 costs 2 (carry 1), bit 1 + 1 = 2 costs 1, and the final carry adds 1, for 2 + 2 + 1 + 1 = 6.
Complexity: O(n) time and O(1) space, where n is the length of s.
class Solution:
def numSteps(self, s: str) -> int:
steps = carry = 0
for i in range(len(s) - 1, 0, -1): # every bit except the leading 1
bit = int(s[i]) + carry # the current lowest bit, with the pending +1
if bit == 1: # odd: add 1 (the carry moves up), then divide
steps += 2
carry = 1
else: # 0 or 2 (i.e. 0 with a carry): even, just divide
steps += 1
return steps + carry # with a carry the leading 1 became "10": one more divide