Hamming Distance
来源:互联网 发布:开淘宝服装店进货渠道 编辑:程序博客网 时间:2024/06/06 07:18
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.
汉明距离就是算两个二进制整数有多少位不同
&按位与,|按位或,^按位异或
要计算汉明距离,只用计算两数异或结果中1的个数
技巧:
把整数减一后的值与原值按位与,相当于把整数二进制中最右边的一个1变成0
//C++class Solution {public: int hammingDistance(int x, int y) { int dist = 0; int n = x ^ y; while(n){ ++dist; n &= n-1; } return dist; }};
另外python中内置bin函数可以将整数转换为二进制字符串,然后用count函数统计字符串中1的个数也可以达到效果
#pythonclass Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x^y).count('1')
阅读全文
0 0
- Hamming Distance
- hamming distance
- hamming distance
- Hamming Distance
- Hamming Distance
- Hamming Distance
- Hamming Distance
- Hamming Distance
- Hamming Distance
- Hamming Distance
- Hamming distance
- Hamming Distance
- Hamming Distance
- hamming distance
- hamming distance
- Hamming Distance
- Hamming Distance
- Hamming Distance
- java编程思想-8
- Laravel快速建站
- 机器学习算法之K-maens算法(以处理matlab下灰度图大米为例)
- Ubuntu Navicat for MySQL安装以及破解方案
- 编译出错的错误记录
- Hamming Distance
- linux入门笔记GCC编译器
- 贪心中“换”的思想
- 程序运行
- 阿里巴巴Java开发手册插件版安装教程
- 处理 /usr/bin/ld: cannot find -lc等编译问题
- 解决跨域问题
- 使用Visual Studio编译器编写程序时不显示窗口或窗口一闪而逝的解决方法
- CodeForces334B