java O(n) solution


  • 0
    2
    public class Solution {
        public int totalHammingDistance(int[] nums) {
            int[] ones = new int[32];
            for (int i : nums) {
                for (int j = 0; j < 31; j++) {
                    if ((i & (1 << j)) != 0) {
                        ones[j]++;
                    }
                }
            }
            int ret = 0;
            for (int i : ones) {
                ret += i * (nums.length - i);
            }
            return ret;
        }
    }
    

Log in to reply
 

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