小编Lia*_*ony的帖子

按时间复杂度 O(1) C++ 代码计算 Byte 中 1 的位数

我搜索了一种算法,该算法通过 O(1) 的时间复杂度以及我在谷歌中找到的内容来计算 Byte 中的个数:

// C++ implementation of the approach  
#include <bits/stdc++.h> 
using namespace std; 
  
int BitsSetTable256[256]; 
  
// Function to initialise the lookup table  
void initialize()  
{  
  
    // To initially generate the  
    // table algorithmically  
    BitsSetTable256[0] = 0;  
    for (int i = 0; i < 256; i++) 
    {  
        BitsSetTable256[i] = (i & 1) +  
        BitsSetTable256[i / 2];  
    }  
}  
  
// Function to return the count  
// of set bits in n  
int countSetBits(int n)  
{  
    return (BitsSetTable256[n & 0xff] …
Run Code Online (Sandbox Code Playgroud)

c++ bit-manipulation bit-shift

5
推荐指数
2
解决办法
321
查看次数

标签 统计

bit-manipulation ×1

bit-shift ×1

c++ ×1