首页 > 其他 > 详细

390 Elimination Game 淘汰游戏

时间:2018-04-15 21:38:44      阅读:163      评论:0      收藏:0      [点我收藏+]

详见:https://leetcode.com/problems/elimination-game/description/

C++:

方法一:

class Solution {
public:
    int lastRemaining(int n) {
        return help(n, true);    
    }
    int help(int n, bool left2right)
    {
        if (n == 1)
        {
            return 1;
        }
        if (left2right)
        {
            return 2 * help(n / 2, false);
        } 
        else
        {
            return 2 * help(n / 2, true) - 1 + n % 2;
        }
    }
};

方法二:

class Solution {
public:
    int lastRemaining(int n) {
        return n==1?1:2*(1+n/2-lastRemaining(n/2));
    }
};

 方法三:

class Solution {
public:
    int lastRemaining(int n) {
        int base = 1, res = 1;
        while (base * 2 <= n) 
        {
            res += base;
            base *= 2;
            if (base * 2 > n)
            {
                break;
            }
            if ((n / base) % 2 == 1)
            {
                res += base;
            }
            base *= 2;
        }
        return res;
    }
};

  详见:https://www.cnblogs.com/grandyang/p/5860706.html

390 Elimination Game 淘汰游戏

原文:https://www.cnblogs.com/xidian2014/p/8849486.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!