English 中文(简体)
阵列中的比值
原标题:Bit count in array
  • 时间:2010-05-02 19:18:09
  •  标签:
  • algorithm

我知道,为了将设定的比值数计算在内,以下法典可以做到:

int  t; // in which we want count how many bits are set
        // for instance, in 3 (011), there are 2 bits set
int count=0;
while (t > 0) {
    t &= (t - 1);
    count++;
}

现举一个例子:

int x[] = {3, 5, 6, 8, 9, 7};

我有以下法典:

int sum = 0;
int count;
for (int i = 0; i < x.length; i++) {
    count = 0;
    while (x[i] > 0){
        x[i] &= (x[i] - 1);
        count++;
    }
    sum += count;
}

然而,这并不奏效。 什么是错的?

最佳回答

你的法典对我课以罚款,但这一期限没有界定——可能是因为你使用 Java,而不是像我首先猜测的那样使用 C。 顺便说一句:

#include <stdio.h>

int main()
{
    int x[]={3,5,6,8,9,7};
    int sum=0;
    int count;
    for (int i=0;i<6;i++){
        count=0;
        while (x[i]>0){
            x[i]&=(x[i]-1);
            count++;
        }
        sum+=count;
    }

   printf("%d
", sum);
}

产出:

12

更简单的办法是在休息室里进行排班,并计算通过时的借方数目。

count = 0;
while (t)
{
    count += t & 1;
    t >>= 1;
}

http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive”rel=“nofollow noretinger”>page 显示一些比较先进的算法,包括使用 look表或cl平行算法。 你们使用的方法在那个页上称为“Brian Kernighan” 。

您还可以看到您的汇编者提供的内容,例如:

int __builtin_popcount (unsigned int x);

为了避免在使用该守则时出现错误的可能性,以获得阵列中的总比数,你可以将其保留为单独的功能,将其称为阵列中的每一部分。 这将简化法典。

问题回答

暂无回答




相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签