Problem · Bit Manipulation

Maximize Consecutive XOR

Learn this problem
MediumIBM logoIBMFULLTIMEOA
See IBM hiring insights

Problem statement

Given an integer n that is divisible by 4, find an integer x satisfying all of the following:

  1. x >= n.
  2. The binary representation of x has the same number of bits as the binary representation of n.
  3. The value v = n XOR (n + 1) XOR ... XOR x is as large as possible.

If several values of x maximize v, return the smallest such x.

Function

getMaxX(n: long) → long

Examples

Example 1

n = 4return = 6

The 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 = 14

The 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 = 30

The 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.
  • n is divisible by 4.

More IBM problems

drafts saved locally
public long getMaxX(long n) {
  // Write your code here.
}
n4
expected6
checking account