The Number of Steps to Reduce a Binary Number to One problem involves reducing a binary number (given as a string) to 1 by performing the following operations:
The goal is to determine the minimum number of steps required to reduce the binary number to 1.
class Solution {
public int numSteps(String s) {
int steps = 0;
int carry = 0;
// Start from the least significant bit and process toward the most significant bit
for (int i = s.length() - 1; i > 0; i--) {
if (s.charAt(i) - '0' + carry == 1) {
// If the bit is 1 (odd), add 1 (carry) and increment steps
carry = 1;
steps += 2; // Add 1 and divide by 2
} else {
// If the bit is 0 (even), just divide by 2
steps += 1;
}
}
// Handle the most significant bit
return steps + carry;
}
}
O(N)
, where N
is the length of the binary string.O(1)
, as we use only a constant amount of extra space.Input: s = "1101"
Output: 6
Explanation:
- "1101" is odd, add 1 โ "1110"
- "1110" is even, divide by 2 โ "111"
- "111" is odd, add 1 โ "1000"
- "1000" is even, divide by 2 โ "100"
- "100" is even, divide by 2 โ "10"
- "10" is even, divide by 2 โ "1"
For a detailed explanation, watch this video: Rearranging Fruits Problem Explanation by NeetCode IO