461. Hamming Distance

题目:

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 ≤ xy < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

链接:https://leetcode.com/problems/hamming-distance/#/description

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 }

更多讨论:https://discuss.leetcode.com/category/590/hamming-distance

posted @ 2017-03-28 02:10  panini  阅读(164)  评论(0编辑  收藏  举报