Advertisement
Guest User

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

a guest
Aug 21st, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement