Leetcode-397:integer Replacement (1 steps for integer change)

Source: Internet
Author: User
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;
    }
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.