leetcode 397 integer replaced

How to appear 1? Minimum 1 times change!

Title follows:
Given a positive integer n, you can do the following:
(1) if n is even, with n / 2 n replacement.
(2) if n is odd, n + 1 can be used or n - 1 n replacement.
The minimum number of replacements needed to 1 n is the number?

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 -> 2 -> 1

Practice analysis topics

  • If there is an even number ==Divisible by 2 == replaced once
  • If there is an odd ==n+1 / n - 1 Alternatively and takes a smaller value wherein

I do not know where you get a glimpse of spectators mysterious yet?
This is not a red fruit IMPLIED

Recursive! ! ! !

Analysis coding

n type operating
odd number return 1(Using the n / 2 number of alternative n +1)+ integerReplacement(n / 2) (Returns the number of alternative n / 2) of
even return 2 ((N-1) / 2 or (n-1) / 2 number of alternative n + 1) + Min (integerReplacement ((t-1) / 2), integerReplacement ((t + 1) / 2)) (Back n-1) in a smaller number of alternative / 2 and (n-1) / 2)

Recursive Dafa is good ヽ (¯ ▽ ¯) Techno

code show as below:

class Solution {
public:
    int cnt = 0;
    int integerReplacement(int n) {
        if(n == 1) return 0;
        if(n % 2 == 0) return 1 + integerReplacement(n / 2);
        else {
            long long t = n;
            return 2 + min(integerReplacement((t-1)/2),integerReplacement((t+1)/2));
        }
    }
};
Published 34 original articles · won praise 0 · Views 589

Guess you like

Origin blog.csdn.net/Luyoom/article/details/103705944