Header Ad

HackerRank Maximizing XOR problem solution

In this HackerRank Maximizing XOR problem solution we have given to integers L and R. we need to find the maximal value of A xor B where l <= a <= b <= r.


Problem solution in Python.

#!/usr/bin/python3
def maxXor(l, r):
    res = 0
    for i in range(l, r+1):
        for j in range(i, r+1):
            if i ^ j > res:
                res = i ^ j
    return res

if __name__ == '__main__':
  l = int(input())
  r = int(input())
  print(maxXor(l, r))


Problem solution in Java.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int L = in.nextInt();
        int R = in.nextInt();
        int ans = Integer.MIN_VALUE;
        for (int A = L; A <= R; A++)
            for (int B = A; B <= R; B++)
                ans = Math.max(ans, A ^ B);
        System.out.println(ans);
    }
}


Problem solution in C++.

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
/*
 * Complete the function below.
 */
int maxXor(int l, int r) {
    int m=0,i,j;
    for(i=l;i<=r-1;i++)
        { for(j=i+1;j<=r;j++)
          m=max(m,i^j);
        }
    return m;  
}

int main() {
    int res;
    int _l;
    cin >> _l;
    
    int _r;
    cin >> _r;
    
    res = maxXor(_l, _r);
    cout << res;
    
    return 0;
}


Problem solution in C.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
/*
 * Complete the function below.
 */
int maxXor(int l, int r) {
int x, y, z, ans = 0;
for (x = l; x <= r; x++)
    for (y = x + 1; y <= r; y++) {
        z = x ^ y;
        if (z > ans) ans = z;
    }
    return ans;
}
int main() {
    int res;
    int _l;
    scanf("%d", &_l);
    
    int _r;
    scanf("%d", &_r);
    
    res = maxXor(_l, _r);
    printf("%d", res);
    
    return 0;
}


Post a Comment

0 Comments