Integer Replacement 🦘

  1. If n is even, replace n with n / 2.
  2. If n is odd, replace n with either n + 1 or n - 1.
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
Input: n = 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
Input: n = 4
Output: 2
  • 1 <= n <= 231 - 1

Solution

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store