博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
12.Hamming Distance(汉明距离)
阅读量:4602 次
发布时间:2019-06-09

本文共 734 字,大约阅读时间需要 2 分钟。

Level:

  Easy

题目描述:

The 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 = 4Output: 2Explanation: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 xor=(x^y);        int t=1;        int res=0;        while(t>0){            if((xor&t)!=0)                res++;            t<<=1;        }        return res;    }}

转载于:https://www.cnblogs.com/yjxyy/p/10706204.html

你可能感兴趣的文章
Codeforces 872C Maximum splitting:数学【分解成合数之和】
查看>>
C++中的struct
查看>>
php join函数使用,很是方便
查看>>
hdu - 2266 How Many Equations Can You Find (简单dfs)
查看>>
UIView属性
查看>>
将博客搬至CSDN
查看>>
Java线程Dump分析工具--jstack【转载】
查看>>
day32(网络编程1)
查看>>
远程服务器git搭建
查看>>
牛人们的博客地址
查看>>
Zabbix是什么?
查看>>
源码:COCO微博
查看>>
面向对象预习随笔
查看>>
大数据概念炒作周期模型
查看>>
排序模型
查看>>
Dede推荐文章与热点文章不显示?
查看>>
React 3
查看>>
Topshelf 使用
查看>>
Linux --Apache服务搭建
查看>>
调试SQLSERVER (二)使用Windbg调试SQLSERVER的环境设置 ------符号文件
查看>>