Java #zeros * #ones solution


  • 0
    D
    public class Solution {
        public int totalHammingDistance(int[] nums) {
            if (nums == null || nums.length <= 1) {
                return 0;
            }
            int[] zeros = new int[32];
            int[] ones = new int[32];
            for (int num : nums) {
                for (int i = 0; i < 32; i++) {
                    int bit = num & (1 << i);
                    zeros[i] += bit == 0 ? 1 : 0;
                    ones[i] += bit == 0 ? 0 : 1;
                }
            }
            int totalDist = 0;
            for (int i = 0; i < 32; i++) {
                totalDist += zeros[i] * ones[i];
            }
            return totalDist;
        }
    }
    

Log in to reply
 

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