Problem · Bit Manipulation
Maximize Consecutive XOR
Learn this problemProblem statement
Given an integer n that is divisible by 4, find an integer x satisfying all of the following:
x >= n.- The binary representation of
xhas the same number of bits as the binary representation ofn. - The value
v = n XOR (n + 1) XOR ... XOR xis as large as possible.
If several values of x maximize v, return the smallest such x.
Function
getMaxX(n: long) → longExamples
Example 1
n = 4return = 6The possible values are 4, 5, 6, and 7. Their consecutive XOR values are 4, 1, 7, and 0, respectively. The maximum is reached when x = 6.
Example 2
n = 8return = 14The valid values have four binary bits. At x = 14, the range XOR equals 15, the largest four-bit value, so 14 is optimal.
Example 3
n = 16return = 30The valid values have five binary bits. Choosing x = 30 makes the range XOR equal 31, which is the largest possible five-bit value.
Constraints
4 <= n <= 10^12.nis divisible by4.