LeetCode "477. Total Hamming Distance"

时间:2021-12-20 03:33:57

Fun one.. the punch line of this problem is quite common in Bit related problems on HackerRank - visualize it in your mind, and you will find: all bits on the same index among all numbers, will not involve other bits on other indices. So, we simply count number of 0s or 1s, on the same bit index from all numbers - we count it vertically..

class Solution {
public:
int totalHammingDistance(vector<int>& nums)
{
int n = nums.size();
if(n < ) return ; // Pass 1: count num of 1s O(31n) -> O(n)
vector<unsigned> cnt();
for(auto v : nums)
for(int i = ; i < ; i ++)
cnt[i] += (v & ( << i)) ? : ; // Pass 2: count
int ttl = ;
for(int i = ; i < ; i ++)
ttl += cnt[i] * (n - cnt[i]); return ttl;
}
};