Java BitSet HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Java BitSet HackerRank Solution. This problem is a part of the HackerRank Java Programming Series.

Java BitSet HackerRank Solution
Java BitSet HackerRank Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Java BitSet HackerRank Solutions

Ezoicreport this adProblem

Java’s BitSet class implements a vector of bit values (i.e.:  () or  ()) that grows as needed, allowing us to easily manipulate bits while optimizing space (when compared to other collections). Any element having a bit value of  is called a set bit.

Given  BitSets,  and , of size  where all bits in both BitSets are initialized to , perform a series of  operations. After each operation, print the number of set bits in the respective BitSets as two space-separated integers on a new line.

Problem Statement: Click Here.

Java BitSet HackerRank Solutions

import java.util.*;
class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        BitSet[] bits = {new BitSet(n), new BitSet(n)};
        for (int i = 0; i < m; i++) {
            String operation = sc.next();
            int x = sc.nextInt();
            int y = sc.nextInt();
            switch (operation) {
                case "AND":
                    bits[x - 1].and(bits[y - 1]);
                    break;
                case "OR":
                    bits[x - 1].or(bits[y - 1]);
                    break;
                case "XOR":
                    bits[x - 1].xor(bits[y - 1]);
                    break;
                case "FLIP":
                    bits[x - 1].flip(y);
                    break;
                case "SET":
                    bits[x - 1].set(y);
                    break;
                default:
                    break;
            }
            System.out.println(bits[0].cardinality() + " " + bits[1].cardinality());
        }
    }
}

Disclaimer: The above Problem (Java BitSet) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Java Priority Queue HackerRank Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad