390. Elimination Game

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int lastRemaining(int n) {
int head = 1;
boolean leftToRight = true;
int step = 1;

while (n > 1) {
if (leftToRight || n % 2 == 1) {
head += step;
}

n /= 2;
step *= 2;
leftToRight = !leftToRight;
}

return head;
}
}

References

390. Elimination Game