Leetcode (397) Integer Replacement

  • 题目:

    Given a positive integer n and you can do operations as follow:

    If n is even, replace n with n/2.
    If n is odd, you can replace n with either n + 1 or n - 1.
    What is the minimum number of replacements needed for n to become 1?

  • 题意:给定一个数,要将它用最少的步数将它变换为1。变换的方式有两种,对于偶数则直接除以二,对于奇数可以选择让它+1或-1

  • 思路:变换得到偶数的话则直接除以二不用考虑。只需要考虑奇数的情况,考虑贪心的方法,对于奇数x,若x+1能被4整除,则x-1只能被2整除,反之亦然。于是对于只能被2整除的数,再除以2的话就会得到奇数又多了至少两项操作,所以,亦有贪心策略选择让变换后的数能被4整除。
  • 注意:有一种反例,也是唯一的反例就是3的时候,因为3-1为2,所以减1更好,其它的情况都符合贪心策略。

  • 代码:

class Solution {
public:
    int integerReplacement(unsigned int n) {
        int cnt=0;
        while (n>1)
        {
            if (n%2 == 0)
            {
                n >>= 1;
            }
            else if (n % 4 == 3)
            {
                n += 1;
            }
            else
            {
                n -= 1;
            }
            cnt++;
        }
        return cnt;
    }
};

光棍节快乐=_=

你可能感兴趣的:(leetcode,leetcode)