HackerRank Java- BitSet




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



  1. import java.util.*;
  2. class Solution {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. int n = sc.nextInt();
  6. int m = sc.nextInt();
  7. BitSet[] bits = {new BitSet(n), new BitSet(n)};
  8. for (int i = 0; i < m; i++) {
  9. String operation = sc.next();
  10. int x = sc.nextInt();
  11. int y = sc.nextInt();
  12. switch (operation) {
  13. case "AND":
  14. bits[x - 1].and(bits[y - 1]);
  15. break;
  16. case "OR":
  17. bits[x - 1].or(bits[y - 1]);
  18. break;
  19. case "XOR":
  20. bits[x - 1].xor(bits[y - 1]);
  21. break;
  22. case "FLIP":
  23. bits[x - 1].flip(y);
  24. break;
  25. case "SET":
  26. bits[x - 1].set(y);
  27. break;
  28. default:
  29. break;
  30. }
  31. System.out.println(bits[0].cardinality() + " " + bits[1].cardinality());
  32. }
  33. }
  34. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube