程式語言 - LeetCode - C++ - 390. Elimination Game



題目:


解答:

class Solution {
public:
    int lastRemaining(int n) {
        int head = 1;
        int step = 1;
        int remain = n;
        bool left = true;

        while (remain > 1) {
            if (left || remain % 2) {
                head += step;
            }

            remain >>= 1;
            step <<= 1;
            left = !left;
        }

        return head;
    }
};