We can use 4 variables to represent the current array.

```
last: the last digit of the array
len: current length of the array
gap: the gap between each digit
i: even/odd counter
```

In each iteration, we have the following transition:

- len = len/2;
- gap = gap*2;
- i = 1 - i;
- last = last - gap
*if (len == odd) or (i == 1) [elimination from right]*

last = last*otherwise*

```
int lastRemaining(int n) {
int last = n, len = n, gap = 1;
bool i = 0;
while (len > 1){
if (len & 1 == 1 || i == 1){
last -= gap;
}
i = !i;
len = len >> 1;
gap = gap << 1;
}
return last;
}
```

Hope you find it helpful.