前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-461-Hamming Distance

leetcode-461-Hamming Distance

作者头像
chenjx85
发布2018-05-22 16:28:13
3970
发布2018-05-22 16:28:13
举报

题目描述:

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

Example:

代码语言:javascript
复制
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.

要完成的函数:

int hammingDistance(int x, int y) 

说明:

给定两个32位的有符号型整数,当每一位不相同时,加上1,输出最后一共有多少位不相同。

代码如下:

代码语言:javascript
复制
    int hammingDistance(int x, int y) 
    {
        int xx,yy,count=0;
        for(int i=0;i<32;i++)
        {
            xx=x&1;
            yy=y&1;
            if(xx!=yy)
                count++;
            x>>=1;
            y>>=1;
        }
        return count;
    }

代码浅显易懂,实测6ms,beats 72.58% of cpp submissions。

这道题在评论区还看到了令人耳目一新的做法,采用异或,当两位相同时输出0,当两位不同时输出1。不过这种做法的时间花费实际还是跟上述代码差不多的。

代码如下:

代码语言:javascript
复制
    int hammingDistance(int x, int y) 
    {
        int result=x^y,t1,count=0;
        for(int i=0;i<32;i++)
        {
            t1=result&1;
            if(t1==1)
                count++;
            result>>=1;
        }
        return count;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档