Skip to content
Problem 397 · LeetCode 397(opens in a new tab)

Integer Replacement

MediumBit manipulation

You are given a positive whole number n. In one step you may change it: if it is even, divide it by 2; if it is odd, add 1 to it or take 1 away from it.

Return the smallest number of steps that turns n into 1.

Example 1

Input:  n = 15
Output: 5
Why:    15 → 16 → 8 → 4 → 2 → 1
2 more examples and the constraints

Example 2

Input:  n = 10
Output: 4
Why:    10 → 5 → 4 → 2 → 1

Example 3

Input:  n = 1
Output: 0
Why:    n is already 1

Constraints

  • 1 ≤ n ≤ 2,147,483,647 (the largest 32-bit signed integer)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try both, with a memoO(log n)
  2. Greedy on the last two bitsO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 2,147,483,647Verdict
Try both, with a memoO(log n)
Passes; easy to argue
Greedy on the last two bitsO(log n)
Best; no memo, no recursion

n = the starting number; log n is its number of bits.

Edge cases to test

  • n = 1. No steps are needed: return 0.
  • n = 3. Going down wins: 3 → 2 → 1 is 2 steps, not 3.
  • The largest n. 2,147,483,647 is all 1s, so the first move adds 1 and passes the 32-bit limit. The answer is 32.
  • A power of two. 1,024 only halves: 10 steps.

Common mistakes

  • Always taking 1 away from an odd number, which loses on long runs of 1s like 15.
  • Forgetting the special case of 3, where adding 1 costs one extra step.
  • Computing n + 1 in a 32-bit int, which overflows for the largest input.

How to talk through it

  1. 1Clarify. Is n at least 1? Can it be the largest 32-bit value? Do I return only the count?
  2. 2Give the recursion. Even has one move, odd has two; add a memo so repeated values are solved once.
  3. 3Look at the bits. Halving drops a trailing 0, so pick the neighbour with more trailing zeros.
  4. 4State the rule. Ends in 01 or is 3: subtract. Ends in 11: add. Use a 64-bit value for the add.
  5. 5Test out loud. Run n = 1, 3, 7 and 15, and check 0, 2, 4 and 5.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?