We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Its quite easy to use, just imagine it as a string that can only contain '0' and '1' characters. You can use set(int index) to set a specific bit from 0 to 1, use get() to return either true or false depending on whether its set or not and other functions like AND to perform operations with more BitSet objects. I would recommend looking at bit-wise operations (&, |, ^, ~), as well as its API: https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html.
Here was my code for the question using BitSet in Java:
import java.util.Scanner;
import java.util.BitSet;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
String word = scanner.nextLine().toLowerCase();
BitSet bits = new BitSet(26);
BitSet tempBits = new BitSet(26);
//Populate initial bit set(otherwise it'll XOR with 0 bits)
for (int i = 0; i < word.length(); i++) {
//minus 'a' to get it in the range on 0 - 25 (ASCII)
bits.set(word.charAt(i) - 'a');
}
//Loop through remaining words
for (int i = 1; i < testCases; i++) {
word = scanner.nextLine().toLowerCase();
for (int j = 0; j < word.length(); j++) {
tempBits.set(word.charAt(j) - 'a');
}
//if both indexes are 1, then the result is 1, else 0
bits.and(tempBits);
tempBits.clear(); //Sets all bits to 0
}
//Prints number of 1 bits
System.out.println(bits.cardinality());
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Gemstones
You are viewing a single comment's thread. Return to all comments →
Its quite easy to use, just imagine it as a string that can only contain '0' and '1' characters. You can use set(int index) to set a specific bit from 0 to 1, use get() to return either true or false depending on whether its set or not and other functions like AND to perform operations with more BitSet objects. I would recommend looking at bit-wise operations (&, |, ^, ~), as well as its API: https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html.
Here was my code for the question using BitSet in Java: