share my easy and clear java solution


  • 0

    just separate numbers on each bit to two parts: odd and even

    1. n & 1 == 1: odd++;
    2. n & 1 == 0: even++;

    and the result on this bit is odd * even.

    for 32-bit integer, we need to loop over 32 times:

    public class Solution {
        public int totalHammingDistance(int[] nums) {
            int result = 0;
            for (int i = 0; i < 32; i++) {
                int odd = 0, even = 0;
                for (int k = 0; k < nums.length; k++) {
                    if ((nums[k] & 1) == 1) {
                        odd++;
                    } else {
                        even++;
                    }
                    nums[k] >>= 1;
                }
                result += odd * even;
            }
            return result;
        }
    }
    

Log in to reply
 

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