O(N) c++ solution


  • 0
    int totalHammingDistance(vector<int>& nums) 
    {
        vector<int> bit_ones(31, 0);
        for (auto num : nums)
        {
            for (int i = 0; i < 31; i++)
            {
                if (num & (1 << i))
                    bit_ones[i]++;
            }
        }
        int result = 0;
        for (auto bit_one : bit_ones)
            result += bit_one * (nums.size() - bit_one);
        
        return result;
    }

Log in to reply
 

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