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

LeetCode | 461. Hamming Distance

2019-11-06 07:55: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 = 4 Output: 2


题意是计算出异或后二进制数中1的个数

直接遍历异或后二进制数组1的个数

效率低,beats 3%

public class Solution { public int hammingDistance(int x, int y) { String str = Integer.toBinaryString(x^y); int count = 0; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == '1') count++; } return count; }}

bitCount

public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); }}

位运算

第一种,异或后再按位判断,beats 36%

public class Solution { public int hammingDistance(int x, int y) { int tmp = x ^ y; int count = 0; while(tmp > 0) { count += tmp & 1; tmp>>=1; } return count; }}

第二种,两个数与1后判断是否相等,beats 55%

public class Solution { public int hammingDistance(int x, int y) { int count = 0; while(x !=0 || y != 0) { if((x&1) != (y&1)) count++; x>>=1; y>>=1; } return count; }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表