Thursday, January 9, 2020

Bitwise Operators - Hacker Rank Solution

Bitwise Operators - Hacker Rank Solution
Here is a breakdown of the problem:
  1. We are given  numbers,  (the size of our set) and  (a constraint on the numbers we choose for our output).
  2. We must have a set of integers from  to  that we'll refer to as .
  3. We must have  integers,  and , that are elements of . These are constrained by the rule that . We implement this with nested loops.
  4. We must find the bitwise ANDbitwise OR, and bitwise XOR for every possible  and . We'll refer to these as , and  respectively.
  5. We must print the maximum , and  denoted by , and  respectively in the output.

void calculate_the_maximum(int n, int k) { int maximum_and = 0, maximum_or = 0, maximum_xor = 0;
for (int i = 1; i <= n; i++) {
    for (int j = i + 1; j <= n; j++) {
        int x = i&j, y = i|j, z = i^j;

        if (x < k && x > maximum_and) {
            maximum_and = x;
        }
        if (y < k && y > maximum_or) {
            maximum_or = y;
        }
        if (z < k && z > maximum_xor) {
            maximum_xor = z;
        }
    }
}

printf("%d\n%d\n%d\n", maximum_and, maximum_or, maximum_xor);
}

3 comments:

Powered by Blogger.