Java Code Explain(Details)


  • 0
    X
    public int totalHammingDistance(int[] nums) {
            int count = 0;
            for (int i = 0; i <32; i++) {
                int zero = 0;
                for (int num : nums) {
                    if ((num & (1 << i)) == 0) {
                        zero++;
                    }
                }
                count += zero * (nums.length - zero);
            }
            return count;
        }
    

    I have seen a few solutions, however, they are very hard to understand. So I decided to provide my solution with graph.
    [4,14,2] in binary view.
    0 1 0 0
    1 1 1 0
    0 0 1 0
    let's look at the first column 0,1,0 there are 2 zeroes and 1 one. so diff = 2 * 1
    second column: 1,1,0 so there are 2 ones and 1 zero. diff = 2 * 1
    thrid column: 0,1,1 so there are 2 ones and 1 zero. diff = 2 * 1
    fourth column: 3 zeroes and 0 one. diff = 3 * 0 = 0
    find any clue? you can add all the diff together which is 2 + 2 + 2 = 6.
    Back to the code, now you can understand. The complexity is 32n.


Log in to reply
 

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