share my easy understanding Java solution, counting amount of 1 in different position and calculate


  • 1
    public class Solution {
    	    public int totalHammingDistance(int[] nums) {
    	    	int length = nums.length;
    	        int[] hammSum = new int[32];
    	        for(int n : nums){//count the amount of 1s in each position
    	        	for(int i = 0; i < 32 && n != 0; i++){
    	        		if((n & 1) == 1) hammSum[i]++;
    	        		n >>>=1;
    	        	}
    	        }
    	        int total = 0;
    	        for(int n : hammSum){//for each position, 1s and 0s combine as the hamming distance at this spot
    	        	total += n * (length-n);
    	        }
    	        return total;
    	    }
    }
    

Log in to reply
 

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