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的个数
效率低,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; }}第一种,异或后再按位判断,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; }}新闻热点
疑难解答