LeetCode-in-Java

3782. Last Remaining Integer After Alternating Deletion Operations

Hard

You are given an integer n.

We write the integers from 1 to n in a sequence from left to right. Then, alternately apply the following two operations until only one integer remains, starting with operation 1:

Return the last remaining integer.

Example 1:

Input: n = 8

Output: 3

Explanation:

Example 2:

Input: n = 5

Output: 1

Explanation:

Example 3:

Input: n = 1

Output: 1

Explanation:

Constraints:

Solution

public class Solution {
    public long lastInteger(long n) {
        final long mask = 0xAAAAAAAAAAAAAAAL;
        return ((n - 1) & mask) + 1;
    }
}