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.
题意,两个数字转为二进制,然后异或一下,判断有多少个1
直接异或判断,简单粗暴
class Solution { private int ham(int num) { int sum = 0; while (num != 0) { if (num%2 == 1) sum ++; num = num/2; } return sum; } public int hammingDistance(int x, int y) { int res = x^y; return ham(res); } }