📜  计算数组中的总设置位

📅  最后修改于: 2022-05-13 01:56:09.023000             🧑  作者: Mango

计算数组中的总设置位

给定一个数组arr ,任务是计算该数组arr所有数字中设置位的总数。

例子:

方法:按照以下步骤解决此问题:

  1. 创建一个变量cnt来存储答案并用0对其进行初始化。
  2. 遍历数组arr的每个元素。
  3. 现在对于每个元素,比如x ,在它大于0时运行一个循环。
  4. 使用(x&1)提取x的最后一位,然后将x右移一位。
  5. 返回cnt作为此问题的答案。

下面是上述方法的实现:

C++
// C++ code for the above approach
 
#include 
using namespace std;
 
// Function to count the total number of set bits
// in an array of integers
int totalSetBits(vector& arr)
{
    int cnt = 0;
    for (auto x : arr) {
 
        // While x is greater than 0
        while (x > 0) {
 
            // Adding last bit to cnt
            cnt += (x & 1);
 
            // Right shifting x by a single bit
            x >>= 1;
        }
    }
    return cnt;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 2, 5, 7 };
    cout << totalSetBits(arr);
}


Java
// Java code for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the total number of set bits
// in an array of integers
static int totalSetBits(int[] arr)
{
    int cnt = 0;
    for (int x : arr) {
 
        // While x is greater than 0
        while (x > 0) {
 
            // Adding last bit to cnt
            cnt += (x & 1);
 
            // Right shifting x by a single bit
            x >>= 1;
        }
    }
    return cnt;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 5, 7 };
    System.out.print(totalSetBits(arr));
}
}
 
// This code is contributed by shikhasingrajput


Python3
# python code for the above approach
 
# Function to count the total number of set bits
# in an array of integers
def totalSetBits(arr):
 
    cnt = 0
    for x in arr:
 
        # While x is greater than 0
        while (x > 0):
 
            # Adding last bit to cnt
            cnt += (x & 1)
 
            # Right shifting x by a single bit
            x >>= 1
    return cnt
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 2, 5, 7]
    print(totalSetBits(arr))
 
# This code is contributed by rakeshsahni


C#
// C# code for the above approach
using System;
 
class GFG {
 
    // Function to count the total number of set bits
    // in an array of integers
    static int totalSetBits(int[] arr)
    {
        int cnt = 0;
        for (int x = 0; x < arr.Length; x++) {
 
            // While x is greater than 0
            while (arr[x] > 0) {
 
                // Adding last bit to cnt
                cnt += (arr[x] & 1);
 
                // Right shifting x by a single bit
                arr[x] >>= 1;
            }
        }
        return cnt;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 5, 7 };
        Console.WriteLine(totalSetBits(arr));
    }
}
 
// This code is contributed by ukasp.


Javascript


输出
7

时间复杂度: O(N)
辅助空间: O(1)