开发者

Fast Range Detection Algorithm

I have an Array of 8 elements: Bin[8]. Bin represents a range container: I receive a number 开发者_C百科N, such as 0 <= N <= 255.

  1. If N < 32 ==> Bin[0] += 1
  2. Else If 32 <= N < 64 ==> Bin[1] += 1
  3. ... etc.

I want a fast solution that does not require an If-Else directive, as I have multiple Bins to handle.

I am using Java, but a solution in any programming language is accepted.

Thank you.


Ensure your number N is indeed 0 <= N <= 255, then simply:

Bin[N/32]++;

Edit: Another poster mentioned shifting right by 5 bits. This will work too, however I feel dividing by 32 shows intent cleaner and any modern compiler will optimize the division away into a bitshift if it's more efficient on the platform you're targeting anyway.


We can use some bitwise operators for this:

binIndex = N >> 5;

Then

Bin[binIndex]++;

This just ignores the low 5 bits of the number, using the top three bits (if N <= 255) as an index into the array of bins.


Just use integer division (truncation):

Bin[N / 32] += 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜