Hamming Distance, java


  • 0
    V

    import java.util.ArrayList;
    import java.util.List;

    public class Question461 {
    public static void main(String args[]){
    Solution s = new Solution();
    System.out.println(s.hammingDistance(8,1));

    }
    
    private static class Solution{
        public int hammingDistance(int x, int y) {
            //get list
            List<Integer> list_x = Decimical_Convert_Binary(x);
            List<Integer> list_y = Decimical_Convert_Binary(y);
    
            int max_size = list_x.size()>list_y.size()?list_x.size():list_y.size();
            int min_size = list_x.size()<list_y.size()?list_x.size():list_y.size();
            int offset = max_size - min_size;
    
            //fill blanks
            if(list_x.size()>list_y.size()){
                for(int i=0; i<offset; i++){
                    list_y.add(Integer.valueOf(0));
                }
            }
            else{
                for(int i=0; i<offset; i++){
                    list_x.add(Integer.valueOf(0));
                }
            }
    
            //compute hamming distance according to the difference
            int cnt = 0;
            for(int i=0;i<list_x.size();i++){
                if(list_x.get(i)!=list_y.get(i)){
                    cnt++;
                }
            }
    
            return cnt;
        }
    
        public List<Integer> Decimical_Convert_Binary(int n){
            List<Integer> list = new ArrayList<Integer>();
            while(n >0){
                int temp = n%2;
                list.add(Integer.valueOf(temp));
                n = n/2;
            }
            return list;
        }
    }
    

    }


Log in to reply
 

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