Java solution counting by bits


  • 0
    Y

    For each bit, we count how many numbers with 1. Then they are in a group, all the others with 0 as another group. Each pair with one from group one and one from group two has a '1' distance. We have count * (n - count) such pairs.

         public int totalHammingDistance(int[] nums) {
             int n = nums.length;
             int res = 0;
             for (int i = 0; i < 32; i++) {
                 int count = 0;
                 for (int j = 0; j < n; j++) {
                     if ((nums[j] >> i) % 2 == 1)
                        count++;
                 }
                 res += count * (n - count);
             }
             return res;
         }
    

    First, I wanted to each number pair, however, I got Time Limit Exceeded error:

        public int totalHammingDistance(int[] nums) {
            int count = 0;
            
            for (int i = 0; i < nums.length - 1; i++)
                for (int j = i + 1; j < nums.length; j++)
                    count += hammingDistance(nums[i], nums[j]);
                    
            return count;
        }
            public int hammingDistance(int x, int y) {
            int n = x ^ y;
            
            int count = 0;
            while (n != 0) {
                count++;
                n = n & (n - 1);
            }
            return count;
        }
    

Log in to reply
 

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