Given two integers, l and r, find the maximal value of a xor b, written a^b, where a and b satisfy the following condition:
l<=a<=b<=r
Example:
Input: l = 10, r = 15
Output: 7
Approach
Java
public class MaximizeXor {public static void main(String[] args) {int l = 10, r = 15;System.out.println(maximizingXor(l, r));}static int maximizingXor(int l, int r) {int res = 0;for (int i = l; i < r; i++) {for (int j = i + 1; j <= r; j++)res = Math.max(i ^ j, res);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;int maximizingXor(int l, int r){int res = 0;for (int i = l; i < r; i++){for (int j = i + 1; j <= r; j++)res = max(i ^ j, res);}return res;}int main(){int l = 10, r = 15;cout << maximizingXor(l, r);return 0;}
No comments:
Post a Comment