Swift Solution Easy to Understand


  • 0
    Y
    func lastRemaining(_ n: Int) -> Int {
        var amount = n
        var right = n
        var left = 1
        var fromLeft = true
        var i = 1
        while right != left{
            if amount % 2 == 1{
                right -= i
                left += i
            }else{
                if fromLeft == false{
                    right -= i
                }else{
                    left += i
                }
            }
            amount /= 2
            fromLeft = !fromLeft
            i *= 2
        }
        return left
    }

Log in to reply
 

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