HackerRank : Week of Code 28 – The Great XOR

By | January 10, 2017
The Great XOR

Source : Hackerrank

The Great XOR : Given a long integer,x , count the number of values of satisfying the following conditions:

  • a^x>x
  • 0<a<x

where and are long integers and is the bitwise XOR operator.

You are given queries, and each query is in the form of a long integer denoting x . For each query, print the total number of values of satisfying the conditions above on a new line.
Input Format
The first line contains an integer, , denoting the number of queries.
Each of the subsequent lines contains a long integer describing the value of for a query.

Output Format
For each query, print the number of values of satisfying the given conditions on a new line.

Sample Input 0

2
2
10

Sample Output 0

1
5

Explanation 0

We perform the following q=2 queries:

  1. For x=2  the only value of satisfying 0<a<x  is  1 . This also satisfies our other condition, as 1^2=3  and 3>x . Because we have one valid and there are no more values to check, we print on a new line.
  2. For x=10 , the following values ofsatisfy our conditions:
    1 ^ 10 = 11
    4 ^ 10 = 14
    5 ^ 10 = 15
    6 ^ 10 = 12
    7 ^ 10 = 13Because there are five valid values of a, we print on a new line.

Solution

The Solution is pretty simple. Its a very simple xor calculation.
Submitted the code successfully.
Will be sharing the code once the competition is over.
Comment to get hints.

Code:

import java.util.Scanner;

public class TheGreatXOR {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int q = scan.nextInt();
		for (int i = 0; i < q; i++) {
			long aa = scan.nextLong();
			int count = 0;
			for (long k = 1; k < aa; k++) { long xor = k ^ aa; if (xor > aa)
					count++;
			}
			System.out.println(count);
		}
	}
}