461. Hamming Distance

柔情只为你懂 2022-05-31 09:51 286阅读 0赞

Description:

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 < 2^31.

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.

Solution:

本质就是两个数的二进制表示所对应位置不同的数量,首先想到的就是通过“异或”
方法一:
利用JDK所提供的方法
Integer.bitCount(int i):返回指定int值的二进制补码表示形式的1位的数量

  1. public class Solution {
  2. public int hammingDistance(int x, int y) {
  3. return Integer.bitCount(x ^ y);
  4. }
  5. }

方法二:
Java中int用32位表示,依次判断x和y的二进制表示的每一位数是否相同

  1. public int hammingDistance(int x, int y) {
  2. int res = 0;
  3. for(int i = 0; i < 32; i++){
  4. res += (x & 1) ^ (y & 1);
  5. x = x >> 1;
  6. y = y >> 1;
  7. }
  8. return res;
  9. }

方法三:(自己首先想到的思路)
首先计算出异或的结果,然后对结果进行计算,找1出现的次数

  1. class Solution {
  2. public int hammingDistance(int x, int y) {
  3. int sum = 0;
  4. int result = x ^ y;
  5. while(result !=0){
  6. if((result&1)== 1){
  7. sum ++;
  8. }
  9. result = result >> 1;
  10. }
  11. return sum;
  12. }
  13. }

上述代码优化后:

  1. public int hammingDistance(int x, int y) {
  2. int xor = x ^ y, count = 0;
  3. for (int i=0;i<32;i++)
  4. count += (xor >> i) & 1;
  5. return count;
  6. }

发表评论

表情:
评论列表 (有 0 条评论,286人围观)

还没有评论,来说两句吧...

相关阅读