XOR of numbers in a given range

Bit Manipulation Problems Medium
  • This problem underlines the XOR bitwise operation widely used in cryptography and communication protocols
  • A real-world application of XOR is the network checksum algorithms in TCP/IP to check the integrity of data
  • XOR is also used in error detection and correction codes used in data storage and transmission
  • This is particularly useful as XOR operation produces a unique output for a unique input, enabling quick detection and correction of errors

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