美文网首页EASY题
461. Hamming Distance [Easy]

461. Hamming Distance [Easy]

作者: DrunkPian0 | 来源:发表于2017-05-31 00:42 被阅读13次

    https://leetcode.com/problems/hamming-distance/description/

    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.

    想速度摸一题Easy题睡觉的,结果还是调试了几次。。
    第一,比较的顺序是从前往后还是从后往前要想清楚。第二,charAt又忘记加单引号了' '。

        public int hammingDistance(int x, int y) {
            String xs = Integer.toBinaryString(x);
            String ys = Integer.toBinaryString(y);
            int count = 0;
            for (int i = 0 ; i < Math.min(xs.length(), ys.length()); i++) {
                if (xs.charAt(xs.length() - 1- i) != ys.charAt(ys.length()-1  - i)) {
                    count++;
                }
            }
            String targetS = xs.length() > ys.length() ? xs : ys;
            for (int j = 0 ; j < targetS.length() - Math.min(xs.length() , ys.length()); j++) {
                if (targetS.charAt(j) != '0') {
                    count++;
                }
            }
            return count;
        }
    

    1 line solution

    https://discuss.leetcode.com/topic/72093/java-1-line-solution-d

    What does come to your mind first when you see this sentence "corresponding bits are different"? Yes, XOR! Also, do not forget there is a decent function Java provided: Integer.bitCount() ~~~

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

    3 line solution,值得看看位运算

    http://blog.csdn.net/xiaochunyong/article/details/7748713

    public int hammingDistance(int x, int y) {
        int xor = x ^ y, count = 0;
        for (int i=0;i<32;i++) count += (xor >> i) & 1;
        return count;
    }
    

    x ^ y的意思是按位异或,也就是说把它们不同的bit变为1,相同的变成0。然后每次右移1位,与1相与,计算1的个数。用到了异或,右移和与运算,不错的训练。

    相关文章

      网友评论

        本文标题:461. Hamming Distance [Easy]

        本文链接:https://www.haomeiwen.com/subject/myddfxtx.html