leetcode 461. Hamming Distance(C语言)

来源:互联网 发布:手机淘宝付款过程 编辑:程序博客网 时间:2024/05/29 02:39

博主立个flag,励志每日刷一题leetcode!

从简单的开始刷,并尽可能地写下思路……(好大的flag,第一天开始!努力ing)


原题:

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:

Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.



本题是要求两个数的汉明距离,真的挺简单的,就是给出两个十进制数x&y,要我们计算出这两个数的二进制有多少位不相同。

那么,我首先要做的就是把一个十进制转化为二进制,进而逐位比较;再设置一个计数器,若两个数不想同就加一,直到两个数的二进制位数都扫描完即可。


贴出我的程序如下:(C代码)

int hammingDistance(int x, int y) {    int cnt=0;//计数器    while(x || y)    {        if(x%2 != y%2)//逐位比较        {            cnt++;        }        x=x/2;        y=y/2;    }    return cnt;}







原创粉丝点击