โ† Back to Index

๐Ÿ“š Number of Steps to Reduce a Binary Number to One โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

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.

๐Ÿงฑ Pattern Template

Simulating Binary Operations

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;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

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"

๐Ÿ’ก Pro Tips

๐ŸŽฅ Video Explanation

For a detailed explanation, watch this video: Rearranging Fruits Problem Explanation by NeetCode IO