461. Hamming Distance [Easy]

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的个数。用到了异或,右移和与运算,不错的训练。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 文/田螺菇凉77 原本是没打算去电影院看这部片名看起来有点中二,剧情狠虐超低泪点狗的电影。以为还是像白百合之前的《...
    田螺菇凉77阅读 432评论 2 4
  • 这件事,一个人做不来。 我是男的。 我在搜集各种社会对“创造性”的观点,试图发现最核心的原因,因为社会学已经是最为...
    jieroarchl阅读 139评论 0 1
  • 第一次走了一万五千步,五公里路,从家到单位走走停停跑跑歇歇,很爽很开心(∩_∩)
    月野兔TT阅读 116评论 0 0
  • 共计1546字丨建议阅读时间3分钟 ▼ 当大象还很小、力气也不大的时候,它便被一根粗锁链栓到了一根牢牢固定的铁柱子...
    南爸的育儿故事阅读 241评论 0 0