Header Ad

HackerRank Bitwise operators in c programming solution

In this HackerRank Bitwise operators in the c programming problem solution, In this challenge, you will use logical bitwise operators. All data is stored in its binary representation. The logical operators, and C language, use 1 to represent true and 0 to represent false. The logical operators compare bits in two numbers and return true or false, 0 or 1, for each bit compared.

  1. Bitwise AND operator & The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. It is denoted by &.
  2. Bitwise OR operator | The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. It is denoted by |.
  3. Bitwise XOR (exclusive OR) operator ^ The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ⊕.

HackerRank Bitwise operators in c programming solution


HackerRank Bitwise operators in c programming problem solution.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.


void calculate_the_maximum(int n, int k) {
    int maxAnd = 0;
    int maxOr = 0;
    int maxXor = 0;

    for (int i=1; i<=n; i++) {
        for (int j=i+1; j<=n; j++) {
            if (((i&j) > maxAnd) && ((i&j) < k)) {
                maxAnd = i&j;
            }
            if (((i|j) > maxOr) && ((i|j) < k)) {
                maxOr = i|j;
            }
            if (((i^j) > maxXor) && ((i^j) < k)) {
                maxXor = i^j;
            }
        }
    }

    printf("%d\n%d\n%d\n", maxAnd, maxOr, maxXor);
}

int main() {
    int n, k;
  
    scanf("%d %d", &n, &k);
    calculate_the_maximum(n, k);
 
    return 0;
}


Second solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.

void calculate_the_maximum(int n, int k) {
    //Write your code here.
    int max_and = 0, max_or = 0, max_xor = 0;
    int v_and = 0, v_or = 0, v_xor = 0;
    for (int i=1; i<=n; i++) {
        for (int j=i+1; j<=n; j++) {
            v_and = i & j;
            v_or = i | j;
            v_xor = i ^ j;
            if (v_and > max_and && v_and < k) max_and = v_and;
            if (v_or > max_or && v_or < k) max_or = v_or;
            if (v_xor > max_xor && v_xor < k) max_xor = v_xor;
        }
    }
    printf("%d\n%d\n%d\n", max_and, max_or, max_xor);
}
int main() {
    int n, k;
  
    scanf("%d %d", &n, &k);
    calculate_the_maximum(n, k);
 
    return 0;
}


Post a Comment

0 Comments