Leetcode 477 Solution

This article provides solution to leetcode question 477 (total-hamming-distance)

https://leetcode.com/problems/total-hamming-distance

Solution

class Solution { public: int totalHammingDistance(vector<int>& nums) { int total = 0;
for (int i = 0; i < 31; i++) { int cnt0 = 0; int cnt1 = 0;
for (int j = 0; j < nums.size(); j++) { if (nums[j] & (1 << i)) cnt1++; else cnt0++; }
total += cnt0 * cnt1; }
return total; } };