C++_O(n)_AC


  • 0

    Time: O(32*n)

    class Solution {
    public:
    int totalHammingDistance(vector<int>& nums) {
        if(nums.empty()) return 0;
        int res = 0;
        for(int k = 1; k <= 32; ++k){
            int zeros = 0, ones = 0;
            for(int i = 0; i < nums.size(); ++i){
                if(nums[i] & 1){
                    ones++;
                }else{
                    zeros++;
                }
                nums[i] = nums[i]>>1;
            }
            res += ones * zeros;
        }
        return res;
    }
    };

Log in to reply
 

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