Compute Hamming Distance How can I make this code snippet better? Those for loops in if don't please me but they are covered with code lines that is dependent to if before and after.

public int hammingDistance(int x, int y) {
    String binx = Integer.toBinaryString(x);
    String biny = Integer.toBinaryString(y);

    int dif = 0;
    StringBuilder sb = new StringBuilder();

    if (binx.length() &gt; biny.length()) {
        dif = binx.length() - biny.length();

        for (int i = 0; i &lt; dif; i++) {
            sb.append(0);      
        }

        biny = sb.toString().concat(biny);
    } else if (biny.length() &gt; binx.length()) {
        dif = biny.length() - binx.length();

        for (int i = 0; i &lt; dif; i++) {
            sb.append(0);      
        }

        binx = sb.toString().concat(binx);
    }

    int dist = 0;

    for (int i = 0; i &lt; binx.length(); i++) {
        if (binx.charAt(i) != biny.charAt(i)) {
            dist++;
        }    
    }

    return dist;
}
You're missing a big simplification.  The hamming distance is the count of ones in x^y, so simply perform that xor and count the set bits.  There should be no need to convert to string.