461. Hamming Distance

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 ≤ x, y < 2^31.


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.

var hammingDistance = function(x, y) {
    var result = 0;
    var n = x ^ y;
    while (n !== 0) {
        result++;
        n &= n - 1;
    }
    return result;
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,350评论 0 33
  • 昨晚睡觉前,天空轰隆隆的响,吓得我不敢睡觉,担心地震(笑哭我自己),不过,问问洛,他和我感受一样一样,瞬间觉得我...
    洛的各各阅读 2,732评论 2 2
  • 什么是"幻",什么是"真"? 其实每一个当下都是"真"。 因为每个瞬间出现的人或事, 都能够激发你...
    日光倾城52fhx阅读 929评论 0 0
  • 这周目标是看完《解忧杂货店》,一页一页看的很慢,却不知不觉翻了过来,看完了。 知道这本书是在元旦的时候,坐车回家,...
    梁木纯阅读 12,469评论 0 2