Hamming Distance

question

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 < 231.

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.

solution

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

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • 不知是否有人和我一样,毕业后尝试过几份工作,忙时感觉时间就是金钱,希望一天干24个小时;闲时翻着手机,刷刷朋友圈默...
    suib阅读 405评论 0 0
  • 突然涌上来的危机感,突然感觉到的无助感。 闪过一霎那的想要离开,但我知道这是没吃饭导致的情绪低落。 别人都在怎么过...
    威景文化阅读 297评论 0 0
  • 起初,我爱的是你的容颜 容颜姣好,及荆之年 肌肤白皙 发短,浅笑连连 起初,我爱的是你的性格 静若处子,奋发向前 ...
    会码字的猫阅读 179评论 0 1
  • 所谓疼,是一种病态的感觉,正如身上贴的胶条,你撕它会疼啊,撕心裂肺,不撕难受,它在破坏你的皮肤,撕掉可能会撕下一层...
    帅气的小提示1阅读 328评论 0 0