Share my C++ solution, easy to understand


  • 0
    V
    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;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.