码迷,mamicode.com
首页 > 其他好文 > 详细

elimination-game

时间:2016-09-21 06:50:28      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/elimination-game/

// 一行代码就可以,不过原理有些复杂
// https://discuss.leetcode.com/topic/58042/c-1-line-solution-with-explanation
// return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2));
// https://discuss.leetcode.com/topic/59293/easiest-solution-o-logn-with-explanation

public class Solution {
    public int lastRemaining(int n) {
        
        boolean isLeft = true;
        int left = n;
        int step = 1;
        int head = 1;
        
        while (left != 1) {
            if (isLeft || left % 2 == 1) {
                head += step;
            }
            step *= 2;
            left /= 2;
            isLeft = !isLeft;
        }
        return head;
        
    }
}

 

elimination-game

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5891211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!