Hamming Distance with Simple Logic


  • 0
    R
     String xValue = Integer.toBinaryString(x);
            StringBuilder a = new StringBuilder();
            String yValue = Integer.toBinaryString(y);
            int count =0 ;
            if(xValue.length() < yValue.length()) {
                int len = yValue.length() - xValue.length();
                for(int i =0 ; i < len; i++)
                    a.append(0);
                xValue = a+xValue;
            }
            if(xValue.length() > yValue.length()) {
                int len = xValue.length() - yValue.length();
                for(int i =0 ; i < len; i++)
                    a.append(0);
                yValue = a+yValue;
            }
            for(int i =0; i < xValue.length(); i++){
                if(xValue.charAt(i) != yValue.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.