Problem Statement A description of the problem can be found on Hackerrank. Solution Create all pairs for all numbers in interval [l, r]. XOR each pair and select maximum. I created solution in: Java JavaScript Scala Ruby All solutions are also available on my GitHub. Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
import java.util.*; public class MaximizingXor { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int l = stdin.nextInt(); int r = stdin.nextInt(); int max = 0; for(int i = l; i <= r; i++) { for(int j = l; j <= r; j++) { int xor = i ^ j; if(xor > max) { max = xor; } } } System.out.println(max); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
function processData(input) { var l = parseInt(input.split("\n")[0]); var r = parseInt(input.split("\n")[1]); var max = 0; for(var i = l; i <= r; i++) { for(var j = l; j <= r; j++) { var xor = i ^ j; if(xor > max) { max = xor; } } } console.log(max); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
import scala.io.Source object MaximizingXor extends App { val lines = Source.stdin.getLines().toList val l = lines(0).toInt val r = lines(1).toInt val maxXor = (l: Int, r: Int) => { var max = 0 (l to r).foreach( i => { (l to r).foreach( j => { val xor = i ^ j if (xor > max) max = xor }) } ) max } println(maxXor(l, r)) } |
Ruby
|
def maxXor(l, r) max = 0 for i in l..r do for j in l..r do xor = i ^ j max = xor if xor > max end end return max end l = gets.to_i r = gets.to_i print maxXor(l, r) |