XOR of numbers in a given range

Bit Manipulation Problems Medium

Given two integers L and R. Find the XOR of the elements in the range [L , R].

Examples:

Input : L = 3 , R = 5

Output : 2

Explanation : answer = (3 ^ 4 ^ 5) = 2.

Input : L = 1, R = 3

Output : 0

Explanation : answer = (1 ^ 2 ^ 3) = 2.

Input : L = 4, R = 10

Constraints

  • 1 <= L <= R <= 109

Hints

  • The XOR of numbers from L to R can be computed using the cumulative XOR from 0 to R and 0 to L−1. This is because XOR(L to R)=XOR(0 to R)⊕XOR(0 to L−1).
  • Compute XOR(L to R) as f(R)⊕f(L-1), where f(N) is the XOR of numbers from 0 to N based on the modulo 4 pattern.

Company Tags

Medtronic GE Healthcare McKinsey & Company IBM Oracle Flipkart HashiCorp DoorDash Philips Healthcare Square KPMG Intel Bain & Company Electronic Arts Broadcom Optum Twilio Byju's MongoDB Cloudflare Nutanix Salesforce Instacart Lyft Stripe Google Microsoft Amazon Meta Apple Netflix Adobe