I'm trying to understand part of this code that was created here to create a my_hashset: https://leetcode.com/problems/design-hashset/discuss/548792/Java-solution-faster-than-99
class HashCode_from_leet {
int[] bitArr;
private static final int MAX = 100000;
private static final int INT_SIZE = Integer.SIZE;
public HashCode_from_leet() {
bitArr = new int[MAX / INT_SIZE + 1];
}
public void add(int key) { //pass in 5
int ind = key / INT_SIZE;
int bit = key % INT_SIZE;
int bitMask = 1 << bit; //QUESTION: why does bitMask = 32?
bitArr[ind] |= bitMask; // QUESTION: what does '|=' mean?
}
// NOTE I REMOVED SOME METHODS
public boolean contains(int key) {
int ind = key / INT_SIZE;
int bit = key % INT_SIZE;
int bitMask = 1 << bit;
return (bitArr[ind] & bitMask) != 0;
}
public static void main(String[] args) {
HashCode_from_leet hfl = new HashCode_from_leet();
hfl.add(5);
System.out.println(hfl.contains(5));
}
}
When I pass in 5 into the add(int key)
method
bitMask = 32
I'm not sure why -- I understand <<
means shift left, so we take 5 and shift it left, but would think that equals 5*10^2?
When you shift left
an integer by X eg: Z =(Y << X)
it will acutally do this operation
: Z = (Y * (2^X))
When you shift right
an integer by X eg: Z =(Y >> X)
it will acutally do this operation
: Z = (Y / (2^X))