Very easy to understand C++ recursion solution


  • 1
    O
        int helper(bool left_to_right, int n) {
            if (n == 1) return 1;
            if (left_to_right) {
                return helper(false, n / 2) * 2;
            } else {
                if (n % 2) {
                    return helper(true, n / 2) * 2;
                } else {
                    return helper(true, n / 2) * 2 - 1;
                }
            }
        }
        
        
    public:
        int lastRemaining(int n) {
            return helper(true, n);
        }
    };
    

Log in to reply
 

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