Title:
Given a positive integer n and you can do operations as follow:
If N is a even, replace N with N/2.
If N is the odd, you can replace n with either n + 1 or n-1.
What's the minimum number of replacements needed for N to become 1? Example:
Example 1:
Input:
8
Output:
3
Explanation:
8, 4, 2, 1
Example 2:
Input:
7
Output:
4
Explanation: 7, 8, 4, 2
, 1 or 7, 6, 3
-&G T 2-1
Problem Resolution:
Given an integer n, the integer is progressively replaced with 1. If an even number is replaced with N/2, an odd number can be replaced with n+1 or n-1. To find the smallest replacement step. Links: leetcode:https://leetcode.com/problems/integer-replacement/description/ Idea label
Mathematical Thinking , dynamic planning , recursive (timeout) answer: The topic seems very easy, but in the process will encounter a lot of problems. Using a simple recursive process, time-outs, high complexity, and math to simplify the recursive process:
Each operation is changed to the next array, and +1, so we record the number of changes can be, when n is even, the direct substitution of N/2, when n is odd, if (n+1)% 4 = = 0, that is, n+1 is a multiple of 4, then n+1 replacement is a step that can be reduced In other cases, replacing with n-1 is always minimal. In addition, the maximum value of int is 2^32-1, so if you use the above method +1 directly, then the programming 2^32 overflow, so we need to deal with this situation separately. Make Int_max to express.
Class Solution {public
:
int integerreplacement (int n) {
if (n = = Int_max) return;
int count = 0;
while (n > 1) {
if (n% 2 = = 0)
n = n/2;
else{
if ((n+1)%4 = = 0 && (n-1! = 2))
n++;
else
n--;
}
count++;
}
return count;
}
};