← DiffPush

XOR of numbers from L to R

Baseline Bit Manipulation · Interview Problems O(1) · O(1)

Merging Beacon Ranges Without Reading Every Vessel

Fleet beacons broadcast IDs in binary, and the merge controller needs the combined XOR of every ID in a contiguous range. Reading millions of beacons one by one is wasteful: the running XOR of 1..n follows a strict four-step rhythm depending on n modulo 4, so the controller computes the rhythm at the range's two ends and cancels the prefix it does not need.

Input: Two integers L and R defining the inclusive range.

Output: The XOR of all integers from L through R.

Constraints

Examples

Example 1

Input: {"l":4,"r":8}
Output: 8
4 ^ 5 ^ 6 ^ 7 ^ 8 collapses to 8 without reading any beacon twice.

Example 2

Input: {"l":1,"r":3}
Output: 0
1 ^ 2 ^ 3 = 3 ^ 3 = 0 — a perfectly canceling range.

Solve this in your browser →

Also on LeetCode ↗