```
public class Solution {
public int lastRemaining(int n) {
return lastRemaining(n, true);
}
private int lastRemaining(int n, boolean right) {
return n == 1 ? 1 : 2 * lastRemaining(n / 2, !right) - ((n % 2 == 0) && !right ? 1 : 0);
}
}
```