首页 > 其他 > 详细

elimination-game

时间:2016-09-21 06:47:57      阅读:112      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!