Hamming Distance solution in Java


  • 0
    X

    、、、
    public class Solution {

        public static int hammingDistance(int x, int y) {
    
           String Sx=Integer.toBinaryString(x);
           String Sy=Integer.toBinaryString(y);
    
            
            int length=Math.abs(Sx.length()-Sy.length());
            char[] CH=new char[length];
            for(int k=0;k<length;k++) {
            	CH[k]='0';	        	
            }
            
            String zero=new String(CH);
    
            
            if(Sx.length()<Sy.length()) {
            	Sx=zero+Sx;
            }
            else if(Sx.length()>Sy.length()) {
            	Sy=zero+Sy;
            }
    
           int count=0;
            for(int i=0;i<Sx.length();i++){
                    if(Sx.charAt(i)!=Sy.charAt(i)){
                        count++;
    
                    }	            
            }
        return count;
    
        }
    

    }
    、、、


Log in to reply
 

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