leetcode/0390.Elimination-Game/README.md
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:
Given the integer n, return the last number that remains in arr.
Example 1:
Input: n = 9
Output: 6
Explanation:
arr = [1, 2,3, 4,5, 6,7, 8,9]
arr = [2,4, 6,8]
arr = [2, 6]
arr = [6]
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 109列表 arr 由在范围 [1, n] 中的所有整数组成,并按严格递增排序。请你对 arr 应用下述算法:
给你整数 n ,返回 arr 最后剩下的数字。
package leetcode
func lastRemaining(n int) int {
start, dir, step := 1, true, 1
for n > 1 {
if dir { // 正向
start += step
} else { // 反向
if n%2 == 1 {
start += step
}
}
dir = !dir
n >>= 1
step <<= 1
}
return start
}