You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:


	Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
	Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.
	Keep repeating the steps again, alternating left to right and right to left, until a single number remains.


Given the integer n, return the last number that remains in arr.

&nbsp;
Example 1:

Input: n = 9
Output: 6
Explanation:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr = [2, 4, 6, 8]
arr = [2, 6]
arr = [6]


Example 2:

Input: n = 1
Output: 1


&nbsp;
Constraints:


	1 &lt;= n &lt;= 109


class Solution:
    def lastRemaining(self, n: int) -> int:
        beg = 1
        len = n
        d = 1
        fromleft = True

        while len > 1:
            if(fromleft or len%2 == 1):
                beg += d
            d <<= 1
            len >>= 1
            fromleft = not fromleft
        
        return beg
class Solution {
    public int lastRemaining(int n) {
        int head = 1;
        int remain = n;
        boolean left = true;
        int step =1;
        
        while(remain > 1){
            if(left || remain%2==1){
                head = head + step;
            }
            remain /= 2;
            step *= 2;
            left = !left;
        }
        return head;
    }
}
class Solution {
public:
    int lastRemaining(int n) {
        bool left=true;
        int head=1,step=1;//step is the difference between adjacent elements.
        while(n>1){
            if(left || (n&1)){//(n&1)->odd
                head=head+step;
            }
            step=step*2;
            n=n/2;
            left=!left;
        }
        return head;
    }
};
var lastRemaining = function(n) {
    let sum=1;  let num=1;  let bool=true;
    while(n>1){       
        if(bool){sum+=num; bool=false;}
        else{if(n%2){sum+=num;} bool=true;}
        num*=2; n=Math.floor(n/2);
    }
    return sum;
}; 
Elimination Game