TopcoderArchiveVisit Topcoder
SRM22 Nov 2011
SRM 543

EllysXors

Problem statement, definition, constraints, and public examples.

Problem Statement

XOR problems became very popular in TopCoder recently. (If you do not know the bitwise operation XOR, see the Notes section for an explanation.) That's why Elly decided to invent one of her own. Fortunately for you, the one she came up with is quite simple. You are given two longs L and R. She wants you to find the XOR of all numbers between L and R, inclusive.

Definition

Class:
EllysXors
Method:
getXor
Parameters:
long, long
Returns:
long
Method signature:
long getXor(long L, long R)
(be sure your method is public)

Notes

  • XOR (exclusive or) is a binary operation, performed on two numbers in binary notation. First, the shorter number is prepended with leading zeroes until both numbers have the same number of digits (in binary). Then, the result is calculated as follows: for each bit where the numbers differ the result has 1 in its binary representation. It has 0 in all other positions.
  • For example 42 XOR 7 is performed as follows. First, the numbers are converted to binary: 42 is 101010 and 7 is 111. Then the shorter number is prepended with leading zeros until both numbers have the same number of digits. This means 7 becomes 000111. Then 101010 XOR 000111 = 101101 (the result has ones only in the positions where the two numbers differ). Then the result can be converted back to decimal notation. In this case 101101 = 45, so 42 XOR 7 = 45.
  • One of the ways to calculate the XOR of more than two numbers A1, A2, ..., An is "A1 XOR (A2 XOR (... XOR An))..))". Since the function is commutative and associative, you can also express it as "A1 XOR A2 XOR ... XOR An" and group the operands in any way you like.
  • It can be proved that the answer is always less than 2*R for the given constraints.

Constraints

  • L and R will be between 1 and 4,000,000,000, inclusive.
  • L will be less than or equal to R.

Examples

  1. 3
    10
    Returns: 8
    ((((((3 XOR 4) XOR 5) XOR 6) XOR 7) XOR 8) XOR 9) XOR 10 = (((((7 XOR 5) XOR 6) XOR 7) XOR 8) XOR 9) XOR 10 = ((((2 XOR 6) XOR 7) XOR 8) XOR 9) XOR 10 = (((4 XOR 7) XOR 8) XOR 9) XOR 10 = ((3 XOR 8) XOR 9) XOR 10 = (11 XOR 9) XOR 10 = 2 XOR 10 = 8.
  2. 5
    5
    Returns: 5
    The XOR of a single number is the number itself.
  3. 13
    42
    Returns: 39
    A bit larger example.
  4. 666
    1337
    Returns: 0
    The answer can be zero.
  5. 1234567
    89101112
    Returns: 89998783
Back to all problems