Reputation: 1
Here in this program of XORing of numbers within the given range, I can't understand the algorithm of how they are finding xor of numbers. It would be pretty good if someone explains how this algorithm works in finding the xor values within the range
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*This program is used to find the xor of numbers within the range
u can enter multiple inputs.Here first enter the numbers of inputs u want to enter then in the next line enter the starting and ending range of the xoring
numbers with space
for example :
Input :
1
2 3
output:
odd
output displays whether the xor value within the given range is odd r not
*/
class XORNEY {
public static void main(String[] args) throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(kb.readLine());
StringBuilder output = new StringBuilder();
while (testCases-- > 0) {
//here without declaring the array dynamically how they are storing all the inputs
String[] input = kb.readLine().trim().split(" ");
long L = Long.parseLong(input[0]);
long H = Long.parseLong(input[1]);
//i am more confused here abt why they are doing this
long count = (H - L) / 2;
if ((L & 1) == 1 || (H & 1) == 1) count++;
output.append((count & 1) == 1 ? "Odd\n" : "Even\n");
}
System.out.print(output);
}
}
Upvotes: 0
Views: 104
Reputation: 2727
here without declaring the array dynamically how they are storing all the inputs
They are just storing each test case line not all the inputs. Each line consist of two numbers separated by space, if you split it by space you get both the numbers on an array.
I am more confused here abt why they are doing this
I can give some ideas -
On a range of numbers, you will get binary numbers ending with an alternate of 0 and 1 sequence. For example -
for each pair of 0, 1
the XOR
will be 1. Now you need to figure out if you are getting even number of pairs or odd number of pairs. Even number of pair will produce even number of 1 to XOR and give you a value ending with 0
that means the ultimate XOR
value is an even
number. And odd
on the other way around.
If you have even number of elements in the range, you are quite sure that you have some pairs of (0, 1)
. But if it's odd, depending on the extra item being 0/1
, your calculation needs to be adjusted.
Upvotes: 1