c++ easy solution, o(n) 116ms


  • 0
    M
        int totalHammingDistance(vector<int>& nums) {
            if (nums.size() <= 1) return 0;
            int ret = 0;
            int len = nums.size();
            vector<int> m(32, 0);
            for (int i = 0; i < nums.size(); ++i) {
                for (int j = 0 ; j < 32; ++j) {
                    m[j] += (nums[i]>>j&1);
                }
            }
            for (int j = 0; j < 32; ++j) {
                ret += m[j] * (len - m[j]);
            }
            return ret;
        }

Log in to reply
 

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