Skip to content

Practice Integer Replacement

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#397
LeetCode Problem

Integer Replacement

Problem Statement

Starting with the positive integer n, repeatedly apply a permitted operation: divide by 2 when n is even, or add 1 or subtract 1 when n is odd. Return the minimum number of operations required to reach 1.

Source: Integer Replacement on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
n = 8
Output
3

# Example 2

Input
n = 7
Output
4

# Example 3

Input
n = 4
Output
2

Constraints

1 <= n <= 2^31 - 1

Related LeetCode Problems

Practice more problems similar to Integer Replacement.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.