Total Hamming Distance

https://leetcode.com/articles/total-hamming-distance/

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int n = nums.size();
        if(n == 0)
        {
            return 0;
        }

        vector<int> bits(32, 0);
        for(int num : nums)
        {
            int cnt = 0;
            int i = 0;
            while(num > 0)
            {
                bits[i] += (num&0x1);
                num >>= 1;
                i++;
            }
        }

        int rst = 0;
        for(int k : bits)
        {
            rst += k*(n-k);
        }

        return rst;
    }
};

results matching ""

    No results matching ""