[LeetCode] 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.

汉明距离。题意是给两个数字,请你求他们之间的hamming distance。hamming distance的定义是两个数字转化成二进制之后,有多少位数字是不同的。比如题目中的例子,1和4有两位数字不同,所以返回2。

思路是首先做XOR运算,然后计算XOR的结果里有多少个1。因为XOR是同位置上的数字,相同为0,不同为1。

时间O(1) - 只有最多32次计算

空间O(1)

Java实现

 1 class Solution {
 2     public int hammingDistance(int x, int y) {
 3         int n = x ^ y;
 4         int count = 0;
 5         while (n != 0) {
 6             count++;
 7             n = n & (n - 1);
 8         }
 9         return count;
10     }
11 }

 

LeetCode 题目总结

posted @ 2020-07-06 06:22  CNoodle  阅读(270)  评论(0编辑  收藏  举报