public class Solution {
public int lastRemaining(int n) {
if(n < 1){
return 0;
}
if(n==1){
return 1;
}
int gap = 1; // gap between 2 elements
int res = 1;
while(gap*2<=n){ // check if there is next element
// from left to right, always delete the first element
res += gap;
// after each run through, gap *=2
gap *= 2;
// from right to left
if(gap*2 <= n){
// check if 1st element needs to be deleted
if((n/gap)%2 == 1){ // only when odd numbers of elements left, we need to delete the 1st element
res += gap;
}
gap *= 2;
}
}
return res;
}
}