```
public int lastRemaining(int n) {
return helper(n, true);
}
int helper(int n, boolean fromLeft) {
if (n == 1) return 1;
if (fromLeft) return 2 * helper(n/2, false);
return 2 * helper(n/2, true) - 1 + (n & 1);
}
```