76ms C++ O(n) solution


  • 0
    X
    class Solution {
    public:
        int totalHammingDistance(vector<int>& nums) {
            vector<int> one(32, 0), zero(32, 0);
            for (int i = 0; i < 32; ++i) {
                for (int j = 0; j < nums.size(); ++j) {
                    if (nums[j] & (1 << i))
                        one[i]++;
                    else
                        zero[i]++;
                }
            }
            int ret = 0;
            for (int i = 0; i < 32; ++i) {
                ret += one[i] * zero[i];
            }
            return ret;
        }
        
    };
    

Log in to reply
 

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