Maximizing XOR

Given two integers, L and R, find the maximal value of A xor B, where A and B satisfy the following condition:

LABR

Input Format

The input contains two lines; L is present in the first line and R in the second line.

Constraints
1LR103

Output Format

The maximal value as mentioned in the problem statement.

Sample Input

10
15

Sample Output

7

Explanation

The input tells us that L=10 and R=15. All the pairs which comply to above condition are the following:
1010=0
1011=1
1012=6
1013=7
1014=4
1015=5
1111=0
1112=7
1113=6
1114=5
1115=4
1212=0
1213=1
1214=2
1215=3
1313=0
1314=3
1315=2
1414=0
1415=1
1515=0
Here two pairs (10, 13) and (11, 12) have maximum xor value 7, and this is the answer.

class Maximizing_XOR
{
static void Main(string[] args)
{
int res;
int _l;
_l = Convert.ToInt32(Console.ReadLine());

int _r;
_r = Convert.ToInt32(Console.ReadLine());

res = maxXor(_l, _r);
Console.WriteLine(res);
Console.ReadKey();
}

private static int maxXor(int _l, int _r)
{
int _max = 0, temp = 0;
for (int i = _l; i <= _r; ++i)
{
for (int j = i; j <= _r; ++j)
{
temp = i ^ j;
if (_max < temp)
{
_max = temp;
}
}
}
return _max;
}
}

Problem source: www.hackerrank.com/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s