Java Hamming Distance


  • 0
    A

    Here is my solution:

        public int hammingDistance(int x, int y) {
            
            
            String binXStr = Integer.toString(x, 2);
            String binYStr = Integer.toString(y,2);
            
            int hamDist = 0;
            
            if (binXStr.length() >= binYStr.length()) {
                for (int i = 1; i  <= binXStr.length() ; i++) {
                    if ( binYStr.length()-i >= 0) {
                        if (Character.getNumericValue(binXStr.charAt(binXStr.length()-i)) != 
                                Character.getNumericValue(binYStr.charAt(binYStr.length() - i)) ) 
                            hamDist++;
                    } else {
                        if (Character.getNumericValue(binXStr.charAt(binXStr.length()-i)) != 0) 
                            hamDist++;
                    }
                }
            } else {
                for (int i = 1; i <= binYStr.length();  i++) {
                    if (binXStr.length() -i >= 0) {
                        if (Character.getNumericValue(binYStr.charAt(binYStr.length()-i)) != 
                                Character.getNumericValue(binXStr.charAt(binXStr.length() - i)) ) 
                            hamDist++;
                    } else {
                        if (Character.getNumericValue(binYStr.charAt(binYStr.length()-i)) != 0) 
                            hamDist++;
                    }
                }            
            }
            
            return hamDist;
            
        }  
    }

Log in to reply
 

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