Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

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

In this guide, we solve Leetcode #1404 Number of Steps to Reduce a Number in Binary Representation to One in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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 1 to it.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Bit Manipulation, String, Simulation

Intuition

The problem structure lets us track state with bitwise operations.

Bit operations are constant time and avoid extra memory.

Approach

Apply XOR/AND/OR and shifts to maintain the required invariant.

Aggregate the result in a single pass.

Steps:

  • Identify a bitwise invariant.
  • Combine values with bit operations.
  • Return the aggregated result.

Example

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.

Python Solution

class Solution: def numSteps(self, s: str) -> int: carry = False ans = 0 for c in s[:0:-1]: if carry: if c == '0': c = '1' carry = False else: c = '0' if c == '1': ans += 1 carry = True ans += 1 if carry: ans += 1 return ans

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the string sss. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy