This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Solution Notebook

Constraints

See the HackerRank problem page.

Test Cases

See the HackerRank problem page.

Algorithm

  • Set max to 0
  • For i in the range (lower, upper) inclusive
    • For j in the range (lower, upper) inclusive
      • Compare i ^ j with max, update max if needed
  • return max

Complexity:

  • Time: O(n^2) - See note below
  • Space: O(1)

Note:

  • TODO: Add more optimal solutions such as those discussed here.

Code


In [1]:
def max_xor(lower, upper):
    result = 0
    for l in range(lower, upper + 1):
        for u in range(lower, upper + 1):
            curr = l ^ u
            if result < curr:
                result = curr
    return result

Unit Test


In [2]:
%%writefile test_maximizing_xor.py
from nose.tools import assert_equal


class TestMaximingXor(object):

    def test_maximizing_xor(self):
        assert_equal(max_xor(10, 15), 7)
        print('Success: test_maximizing_xor')


def main():
    test = TestMaximingXor()
    test.test_maximizing_xor()


if __name__ == '__main__':
    main()


Overwriting test_maximizing_xor.py

In [3]:
%run -i test_maximizing_xor.py


Success: test_maximizing_xor