Here's my solution , any solutions that are better in performance?


  • 0
    C

    '''
    public int hammingDistance(int x, int y) {
    int count = 0;
    String str1 = Integer.toBinaryString(x);
    String str2 = Integer.toBinaryString(y);
    char[] max = (str1.length() > str2.length()? str1.toCharArray():str2.toCharArray());
    char[] mini = (str1.length() > str2.length()? str2.toCharArray():str1.toCharArray());
    // System.out.println(max);
    // System.out.println(mini);
    int maxLength = max.length-1;
    int miniLength = mini.length-1;
    for(int i = 0; i<mini.length;i++){
    if(max[maxLength] != mini[miniLength]){
    count++;
    }
    miniLength--;
    maxLength--;
    }
    for(int i = 0; i <= max.length - mini.length-1; i++){
    if(max[i] != '0'){
    count++;
    }
    }

    	System.out.println(count);
    	return count;
    			
    }
    

    '''


Log in to reply
 

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