Java O(log N) solution. Clear code


  • 0
    Y

    '''
    public int lastRemaining(int n) {
    return lastRemaining(n, true);
    }

    private int lastRemaining(int n, boolean left) {
        if (n <= 1) {
            return 1;
        }
        
        int index = lastRemaining(n >> 1, !left);
        if ((n & 0x1) == 0) {
            if (left) {
                return index << 1;
            } else {
                return (index << 1) - 1;
            }
        } else {
            return index << 1;    
        }
    }
    

    '''


Log in to reply
 

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