SHARE
TWEET

477. Total Hamming Distance | Time:O(n) | Space: O(1)

a guest Aug 21st, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Problem: https://leetcode.com/problems/total-hamming-distance/
  2. // Solution: https://leetcode.com/problems/total-hamming-distance/discuss/247217/Java-Solutions
  3.  
  4. class Solution {
  5.     public int totalHammingDistance(int[] nums) {
  6.         int total = 0;
  7.        
  8.         for(int i = 0; i < 32; i++) {
  9.             int countOnes = 0;
  10.             int countZeroes = 0;
  11.            
  12.             for (int x: nums) {
  13.                 if((x >> i & 1) == 1) {
  14.                     countOnes ++;
  15.                 } else {
  16.                     countZeroes ++;
  17.                 }
  18.             }
  19.            
  20.             total += countZeroes * countOnes;
  21.         }
  22.        
  23.         return total;
  24.     }
  25. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top