1526. XOR Across a Range
An archivist numbers the boxes in a long shelf from lo to hi inclusive and wants a quick checksum: the XOR of all the box numbers in that range, lo ^ (lo+1) ^ ... ^ hi. The shelf can be enormous, so looping over every number is far too slow.
Return the checksum as a 64-bit integer. The prefix XOR 0 ^ 1 ^ ... ^ x follows a pattern that repeats with period 4 depending on x mod 4, so the range value can be derived from two prefix values in constant time. Treat the prefix XOR of a negative bound as 0. Aim for O(1) time and O(1) extra space; the result is always below 2^50.
Example 1
- Input:
- lo = 3, hi = 9
- Output:
- 2
- Explanation:
3^4^5^6^7^8^9 equals 2.
Example 2
- Input:
- lo = 5, hi = 5
- Output:
- 5
- Explanation:
A single number is its own XOR, so the answer is 5.
Constraints
0 ≤ lo ≤ hi ≤ 1015
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(1)
- Space
- O(1)