```
public int lastRemaining(int n) {
return helper(1,n,1,true);
}
// start is the current first number
// num is count of remaining numbers
// diff is the interval between two next-to-each-other numbers
// isFromLeft is from left or from right
private int helper(int start,int num,int diff,boolean isFromLeft){
if(num==1){
return start;
}else{
//if isFromLeft, new start is the second number
//if isFromRight, new start is the first number if count is even
// new start is the second number if count is odd
int newStart = (isFromLeft||num%2==1)?(start+diff):start;
return helper(newStart,num/2,diff*2,!isFromLeft);
}
}
```