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;
        
    }
}

 

相关文章:

  • 2021-07-12
  • 2021-06-19
  • 2022-12-23
  • 2021-04-29
  • 2021-10-06
  • 2021-05-23
  • 2021-11-23
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-14
  • 2022-12-23
  • 2021-06-19
相关资源
相似解决方案