FastPrepCount Set Bits with a Byte Lookup Table

Count Set Bits with a Byte Lookup Table

Microsoft logoMicrosoft● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given an array of signed 32-bit integers values, return the total number of one bits across their 32-bit two's-complement representations.

Precompute the set-bit count for every byte value from 0 through 255, then use four table lookups per integer.

Function

countSetBits(values: int[]) → long

Examples

Example 1

values = [0,1,255,256]return = 10

The values contain 0, 1, 8, and 1 set bits respectively.

Example 2

values = [-1]return = 32

Signed -1 has all 32 bits set in two's-complement representation.

Constraints

  • 0 <= values.length <= 1000000
  • Every value is a signed 32-bit integer.

More Microsoft problems

See Microsoft hiring insights
public long countSetBits(int[] values) {
  // Write your code here.
}
values[0,1,255,256]
expected10
Checking account…