Header Ad

HackerRank The Great XOR problem solution

In this HackerRank The Great XOR problem solution we have given Q queries and each query is in the form of a long integer denoting X. for each query we need to print the total number of values of A satisfying the conditions given below.

A XOR X > X

0 < A < X

HackerRank The Great XOR problem solution


Problem solution in Python.

#!/bin/python3

import sys


q = int(input().strip())
for a0 in range(q):
    x = int(input().strip())
    binary = list(bin(x))[2:]
    binary.reverse()
    summ = 0
    for idx, item in enumerate(binary):
        if item == "0":
            summ += 2**idx

    print(summ)


Problem solution in Java.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long[] powersOf2 = new long[64];
        powersOf2[0] = 1;
        for (int i = 1; i < 64; i++) {
            powersOf2[i] = powersOf2[i - 1] << 1;
        }
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            long x = in.nextLong();

            long count = 0;
            int position = 0;
            while (x > 1) {
                if ((x & 1) == 0) {
                    count += powersOf2[position];
                }
                x >>= 1;
                position++;
            }
            System.out.println(count);
        }
    }

}


Problem solution in C++.

#include <iostream>

using namespace std;

long long n, q, ans;
int main(){
    cin >> q;
    while(q --){
        cin >> n;
        ans = 1;
        while(ans <= n){
            ans *= 2;
        }
        ans /= 2;
        cout << ans - 1 - (n - ans) << endl;
    }
}


Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

long fun3(long x) {
    long l;
    for(l=1;l<x;) {
        l *= 2; l++;
    }

    return l^x;
}

int main(){
    int q; 
    scanf("%d",&q);
    for(int a0 = 0; a0 < q; a0++){
        long x; 
        scanf("%ld",&x);
        printf("%ld\n", fun3(x));
    }
    return 0;
}


Post a Comment

0 Comments