Back to problems

Depth-First Search Problem

Algorithm · Perplexity · Medium

Starting with a positive integer n, reduce it until it becomes 1. On each move, halve the value when it is even; when it is odd, you may replace it with either n - 1 or n + 1. Determine the fewest moves required. Input One integer n, where 1 ≤ n ≤ 10^9 Output Print an integer equal to the minimum number of moves needed to reach 1. Example Input: 12 Output: 4 Explanation: 12 -> 6 -> 3 -> 2 -> 1 Input: 15 Output: 5 Explanation: 15 -> 16 -> 8 -> 4 -> 2 -> 1 Example Explanation:…

Checking your access…