leetcode 461. Hamming Distance
来源:互联网 发布:java哪些源码值得看 编辑:程序博客网 时间:2024/06/18 05:45
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 = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑The above arrows point to positions where the corresponding bits are different.该题是主要理解汉明距离。两个等长字符串之间的汉明距离是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。比如,The Hamming distance between 1011101 and 1001001 is 2.
那么这题我就可以对x,y进行异或运算,然后统计得到的数字的二进制表达中有几个1即可。
一开始,我是用不断除以2的方式来获取数字二进制中有几个1,然而time out了。只好右移,和1做”与“运算。
public class Hamming_Distance_461 {public int hammingDistance(int x, int y) { int xor=x^y; int num=0; for(int i=0;i<32;i++){ num+= (xor>>i)&1; } return num;}public static void main(String[] args) {// TODO Auto-generated method stubHamming_Distance_461 h = new Hamming_Distance_461(); System.out.println(h.hammingDistance(1,4));}}然后我发现有牛人直接用java的函数,这个函数我都没听说过。
public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); }}查了一下,bitCount方法返回指定int值的二进制补码表示形式的1位的数量。
附:
Java中的位运算符:
>>表示右移,如果该数为正,则高位补0,若为负数,则高位补1;
>>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0。
补充:
<< 是与>>对应的左移运算符,表示将exp1向左移动exp2位,在低位补0。其实,向左移动n位,就相当于乘以2^n。
左移没有<<<运算符!
0 0
- LeetCode 461. Hamming Distance
- 【Leetcode】461. Hamming Distance
- LeetCode 461. Hamming Distance
- LeetCode - 461. Hamming Distance
- LeetCode-461. Hamming Distance
- 【LeetCode】 461. Hamming Distance
- Leetcode-461. Hamming Distance
- Leetcode 461. Hamming Distance
- LeetCode--461. Hamming Distance
- 461. Hamming Distance [LeetCode]
- [LeetCode]461. Hamming Distance
- leetcode 461. Hamming Distance
- Leetcode 461. Hamming Distance
- LeetCode 461. Hamming Distance
- 【LeetCode】461. Hamming Distance
- LeetCode-461. Hamming Distance
- LeetCode | 461. Hamming Distance
- [LeetCode]461.Hamming Distance
- HDU5540 Secrete Master Plan(水题)(2015CCPC)
- 分区分配方案
- iOS 删除线不显示问题 10.3以后
- 能上QQ却上不了网页
- Spring---AOP基本概念以及Advice5种类型的通知注解应用实例
- leetcode 461. Hamming Distance
- python安装配置Theano ImportError:cannot import name 'configparser'
- 互换两个变量,不使用中间变量
- POJ 3067
- JS原型设计模式(二)
- pdf 转 word
- mysql索引知识
- Android http Post 传文件
- 【linux】Makefile 基本知识