Number of Steps to Reduce a Binary Number to One
Updated
Problem statement
You are given a binary string binary representing a positive integer.
Repeatedly apply the following rule until the value becomes 1:
- If the current value is even, divide it by
2. - If the current value is odd, add
1.
Return the number of operations performed.
The binary string may be too long for a built-in integer type, so process it without converting the complete value to an integer.
Function
numSteps(binary: String) → intExamples
Example 1
binary = "1101"return = 6The values are 13 -> 14 -> 7 -> 8 -> 4 -> 2 -> 1, which uses 6 operations.
Example 2
binary = "10"return = 1The value 2 is even, so one division produces 1.
Example 3
binary = "1"return = 0The value is already 1, so no operation is needed.
Constraints
1 <= binary.length <= 500.binarycontains only0and1.binary[0] == '1'.
More Deloitte Online Assessment questions
- Seventh Nearest PalindromeOA · Seen May 2026
- Minimum Deletions for a Non-PalindromeOA · Seen Jul 2025
- Minimum-Cost Solar Rooftop AllocationOA · Seen Jul 2025
- Pair Elements with Even SumsOA · Seen Jul 2025
- Count Divisible PermutationsOA · Seen Jan 2025
- Largest Element in an ArrayOA · Seen Nov 2024
- Install Carbon FiltersOA · Seen Oct 2023
- Longest Substring with Even OccurrencesOA · Seen Oct 2023
- Maximum Sum RectangleOA · Seen Apr 2022
- Annual Bank Balance with Monthly Card FeesOA · Seen Jan 2022
Similar questions at other companies
- Decrement a Binary Number and Count Its OnesZipRecruiter · OAZipRecruiter interview questions
- Operations to Reduce a Binary String Value to ZeroMarshall Wace · OAMarshall Wace interview questions
- RNG-Based Tree Document CodecBaseten · PHONE SCREENBaseten interview questions
- Ordered IP FirewallDatabricks · PHONE SCREENDatabricks interview questions
- CIDR IPv4 Range IteratorOpenAI · PHONE SCREENOpenAI interview questions
- Reliable LLM Call with Independent Retry BudgetsStripe · OAStripe interview questions
- Minimum No-Repeat Segments After One Character RemovalSalesforce · OASalesforce interview questions
- Repeated Mirror XORMathWorks · OAMathWorks interview questions
- Tennis Game ScoreAbridge · OAAbridge interview questions
- Compress Editor Actions into Operational Transform OperationsReplit · OA · PHONE SCREEN · ONSITE INTERVIEW