Algorithm to calculate the number of 1s for a range of numbers in binary

前端 未结 6 1937
再見小時候
再見小時候 2021-01-30 00:39

So I just got back for the ACM Programing competition and did pretty well but there was one problem that not one team got.

The Problem.

6条回答
  •  清酒与你
    2021-01-30 00:51

    You can solve this efficiently as follows:

    ret = 0;
    for (i = 1; i <= 64; i++) {
      if (computeK(i) != desiredK) continue;
      ret += numBelow(HIGH, i) - numBelow(LO - 1, i);
    }
    return ret;
    

    The function numBelow(high, numSet) computes the number of integers less than or equal to high and greater than zero that have numSet bits set. To implement numBelow(high, numSet) efficiently, you can use something like the following:

    numBelow(high, numSet) {
      t = floor(lg(high));
      ret = 0;
      if (numBitsSet(high) == numSet) ret++;
      while (numSet > 0 && t > 0) {
        ret += nchoosek(t - 1, numSet);
        numSet--;
        while (--t > 0 && (((1 << t) & high) == 0));
      }
      return ret;
    }
    

提交回复
热议问题