题目:
The 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.
链接:
3/27/2017
1 public class Solution { 2 public int hammingDistance(int x, int y) { 3 int z = x ^ y; 4 int c = 1, count = 0; 5 while (z != 0) { 6 if ((z & c) != 0) count++; 7 z >>= 1; 8 } 9 return count;10 }11 }
其他人作法:
1. 使用自带函数
1 public class Solution {2 public int hammingDistance(int x, int y) {3 return Integer.bitCount(x ^ y);4 }5 }
更多讨论: