Leetcode 1404: Number of Steps to Reduce a Number in Binary Representation to One

grid47
grid47
Exploring patterns and algorithms
Jun 19, 2024 6 min read

You are given a binary string representing a non-negative integer. The task is to determine the number of steps required to reduce this number to 1, following the rules: divide by 2 if the number is even, or add 1 if it is odd. Return the total number of steps required.
Problem
Approach
Steps
Complexity
Input: The input is a binary string representing a non-negative integer.
Example: "1111"
Constraints:
• 1 <= s.length <= 500
• s consists of characters '0' or '1'
• s[0] == '1'
Output: The output is an integer representing the number of steps required to reduce the given number to 1.
Example: 7
Constraints:
• The output should be the total number of steps to reduce the number to 1.
Goal: The goal is to count how many operations are needed to reduce the number to 1.
Steps:
• Convert the binary string to a decimal integer.
• For each step, check if the number is odd or even.
• If the number is odd, increment it by 1. If it's even, divide it by 2.
• Keep track of the number of operations until the number becomes 1.
Goal: The input binary string should be between 1 and 500 characters long, and the string must represent a non-negative integer.
Steps:
• The string contains only '0's and '1's.
• The first character of the string is '1'.
Assumptions:
• The input string is valid and represents a non-negative integer.
• The problem will always have a solution as the number will eventually reduce to 1.
Input: Input: "1111"
Explanation: The binary representation '1111' corresponds to the number 15. It takes 7 steps to reduce 15 to 1 by following the rules of even and odd operations.

Input: Input: "100"
Explanation: The binary representation '100' corresponds to the number 4. It takes 3 steps to reduce 4 to 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus