I need to count the number of 1s in a binary representation of an integer. The two requirements are:
1) Must use table lookup 2) Must use XOR bitwise operator
So far, I think I have a table lookup that would work:
const generateLookupTable = (int) => {
const range = Array.from({length: int}, (x,i) => i);
const toBinary = (table, i) => {
const binary = (i >>> 0).toString(2);
table[i] = binary;
return table;
}
const lookupTable = range.reduce(toBinary, {})
return lookupTable;
};
This prints out something like:
generateLookupTable(7)
{0: "0", 1: "1", 2: "10", 3: "11", 4: "100", 5: "101", 6: "110"}
I'm stumped on how I would use XOR to solve this problem (or why I would even use a lookup table). I feel like I could solve this easily by converting the int to a binary and then just looping through each character and summing up the 1s I see. However, the requirements are making it difficult.