首页 > 学院 > 开发设计 > 正文

LeetCode第一天

2019-11-08 01:32:03
字体:
来源:转载
供稿:网友

LeetCode 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次方.

示例: 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.

代码如下:

class Solution {public: int hammingDistance(int x, int y) { int a[31],b[31]; int c=0; for(int i=0;i<31;i++) { if(x%2!=0) { a[i]=1; x=x/2; } else { a[i]=0; x=x/2; } if(y%2!=0) { b[i]=1; y=y/2; } else { b[i]=0; y=y/2; } if(a[i]!=b[i]) c++; } return c; }};汉明距离(Hamming Distance)汉明距离是以理查德·卫斯里·汉明的名字命名的。在信息论中,两个等长字符串之间的汉明距离是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。例如: 1011101 与 1001001 之间的汉明距离是 2。 2143896 与 2233796 之间的汉明距离是 3。 “toned” 与 “roses” 之间的汉明距离是 3。 摘选自百度百科
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表