14 line easy understanding C++ O(n) solution

  • 0

    According hamming distance definition, for each bit, the distance will add 1 iff the two numbers have different values (one is 1 and the other is 0) on that bit. Then we can divide all numbers to 2 groups based on the value of a specific bit by counting the numbers which the bit set to 1. Let's say we have total n numbers and m of them has the first bit set to 1. So, we can easily figure out that each number of m numbers and each of the rest n-m number will increase the distance by 1. The total distance on that bit will be m * (n-m). Repeat this for every bits (total 32 in this problem) and sum them up.

    class Solution {
        int totalHammingDistance(vector<int>& nums) {
            int res = 0;
            for (int i = 0; i < 32; i++) {
                int count = 0;
                for (int j = 0; j < nums.size(); j++) {
                    count += 1 & (nums[j] >> i);
                res += (nums.size() - count) * count;
            return res;

Log in to reply

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