I use two methods: lastRemaining(), which is count from left to right, and backLastRemaing(), which is count from right to left, then we have

lastRemaining(n)=backLastRemaining(n/2) whatever n is.

backLastRemaining(n)=2*lastRemaining(n/2), if n is odd,
backLastRemaining(n)=2*lastRemaining(n/2)-1, if n is even.

```
public int lastRemaining(int n)
{
if(n==1)
return 1;
return 2*backLastRemaining(n/2);
}
public int backLastRemaining(int n)
{
if(n==1)
return 1;
if(n%2==0)
return 2*lastRemaining(n/2)-1;
return 2*lastRemaining(n/2);
}
```