```
class Solution {
public:
int lastRemaining(int n) {
int first_number = 1;//first number in current list
int distance = 1;
while (distance * 2 <= n)
{
first_number += distance;//left -> right
distance *= 2;
if (distance * 2 > n)
break;
//right->left
if ((n / distance) % 2 != 0)//number of the remaining numbers is odd
first_number += distance;
distance *= 2;
}
return first_number;
}
};
```