LeetCode 461

Question:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ xy < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ?   ?

The above arrows point to positions where the corresponding bits are different.

 

My solution:

public class Solution {
public int hammingDistance(int x, int y) {
 int count = 0;
 String x1 = Integer.toBinaryString(x);
 String y1 = Integer.toBinaryString(y);
 if(x1.length() < y1.length()){
 x1 = addBefore(x1,y1);
 }
 if(x1.length() > y1.length()){
 y1 = addBefore(y1,x1);
 }
 for(int i =0;i<x1.length();i++){
 if(x1.charAt(i) != y1.charAt(i)){
 count +=1;
 }
 }
 return count;
 }
 public String addBefore(String some,String object){
 String someone = some;
 while(someone.length()<object.length()){
 someone = "0" + someone;
 }
 return someone;
 }
}

 

Explain:

first convert object number to a binary value in String form.

second, add zero to the smaller result until two String have same length.

finally,  compare two string by char and add 1 when char at same position is different.

 

Best solution in Java:

public class Solution { 
    public int hammingDistance(int x, int y) { 
        return Integer.bitCount(x ^ y); 
    } 
}

use x^y  to return a value which for each bit in x and y, if same, then 0, else 1;

count number of 1 inside this value in the result.

 

 

留下评论