C++ solution calculating Hamming distance by bit


  • 0
    K
    class Solution {
    public:
        int totalHammingDistance(vector<int>& nums) {
            int res=0;
            vector<int>cnt(32,0);
            for(int num:nums)
            {
                int i=0;
                while(num)
                {
                    cnt[i++]+=num&1;
                    num>>=1;
                }
            }
            int n=nums.size();
            for(int m:cnt)
                res+=m*(n-m);
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.