LeetCode 397, Medium. Topics: Dynamic Programming, Greedy, Bit Manipulation, Memoization. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:
Problem
Given a positive integer n, you can apply one of the following operations:
- If
n is even, replace n with n / 2.
- If
n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Examples
Constraints
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026