Hamming Distance

http://www.lintcode.com/zh-cn/problem/hamming-distance/

public class Solution {
    /**
     * @param x: an integer
     * @param y: an integer
     * @return: return an integer, denote the Hamming Distance between two integers
     */
    public int hammingDistance(int x, int y) {
        // write your code here
        String s1 = Integer.toBinaryString(x);
        String s2 = Integer.toBinaryString(y);
        int res = 0;
        int length = Math.max(s1.length(), s2.length());
        while (s1.length() < length) {
            s1 = '0' + s1;
        }
        while (s2.length() < length) {
            s2 = '0' + s2;
        }

        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                res++;
            }
        }
        return res;
    }
}

你可能感兴趣的:(Hamming Distance)