📜  使用位集计算范围内的设置位数

📅  最后修改于: 2021-05-25 08:08:23             🧑  作者: Mango

给定较大的二进制数。任务是计算从LR (基于1的索引)的给定范围内的1的数量。

例子:

方法:

  • 将大小为len的字符串转换为大小为N的位集
  • 不需要在位集的左侧的(N – len)+(L – 1)位,在右侧的(N – R)位。
  • 使用左移和右移按位运算可以有效地删除那些位。
  • 现在,L的左侧和R的右侧全为零,因此只需使用count()函数即可获取位集中的1的计数,因为除[L,R]以外的所有位置均为’0’。

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
#define N 32
  
// C++ function to count 
// number of 1's using bitset
int GetOne(string s, int L, int R)
{
  
    int len = s.length();
  
    // Converting the string into bitset
    bitset bit(s);
  
    // Bitwise operations
    // Left shift
    bit <<= (N - len + L - 1);
  
    // Right shifts
    bit >>= (N - len + L - 1);
    bit >>= (len - R);
  
    // Now bit has only those bits
    // which are in range [L, R]
  
    // return count of one in [L, R]
    return bit.count();
}
  
// Driver code
int main()
{
  
    string s = "01010001011";
  
    int L = 2, R = 4;
  
    cout << GetOne(s, L, R);
  
    return 0;
}


Python3
# Python3 implementation of above approach 
  
N = 32 
  
# function for converting binary
# string into integer value
def binStrToInt(binary_str):
    length = len(binary_str)
    num = 0
    for i in range(length):
        num = num + int(binary_str[i])
        num = num * 2
    return num / 2
  
  
# function to count 
# number of 1's using bitset 
def GetOne(s, L, R) : 
  
    length = len(s); 
  
    # Converting the string into bitset 
    bit = s.zfill(32-len(s));
      
    bit = int(binStrToInt(bit))
  
    # Bitwise operations 
    # Left shift 
    bit <<= (N - length + L - 1); 
  
    # Right shifts 
    bit >>= (N - length + L - 1); 
    bit >>= (length - R); 
  
    # Now bit has only those bits 
    # which are in range [L, R] 
  
    # return count of one in [L, R] 
    return bin(bit).count('1'); 
  
  
# Driver code 
if __name__ == "__main__" : 
  
    s = "01010001011"; 
  
    L = 2; R = 4; 
  
    print(GetOne(s, L, R)); 
      
# This code is contributed by AnkitRai01


输出:
2