zoukankan      html  css  js  c++  java
  • 力扣461. 汉明距离

    461. 汉明距离

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
    给出两个整数 x 和 y,计算它们之间的汉明距离。

    注意:
    0 ≤ x, y < 231.

    思路一:

    1. 先用异或运算符求出x异或y的结果,这个异或运算符的结果的1的个数即是我们要求的汉明距离
    2. 循环移位,每次取xor的最低位

     1 class Solution {
     2     public int hammingDistance(int x, int y) {
     3         int count = 0;
     4         int xor = x ^ y;
     5         while(xor != 0){
     6             count += xor & 1;
     7             xor = xor >> 1;     // xor右移一位
     8         }
     9         return count;
    10     }
    11 }

    复杂度分析:

    时间复杂度:O(1),Java 中 Integer 的大小是固定的,处理时间也是固定的。 32 位整数需要 32 次迭代。
    空间复杂度:O(1),使用恒定大小的空间。

    思路二:

    使用布赖恩·克尼根算法,xor & (xor - 1)即可移除xor最右边的那个1,省去了移除0的过程,减少了迭代次数

     1 class Solution {
     2     public int hammingDistance(int x, int y) {
     3         int count = 0;
     4         int xor = x ^ y;
     5         while(xor != 0){
     6             count += 1;
     7             xor = xor & (xor - 1);     // 每次移除最右边的一个1
     8         }
     9         return count;
    10     }
    11 }

    复杂度分析:

    时间复杂度和空间复杂度都是O(1),但是迭代次数小于法一

    作者:LeetCode
    链接:https://leetcode-cn.com/problems/hamming-distance/solution/yi-ming-ju-chi-by-leetcode/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    DB2
    Data Queue
    QMQY
    CMD(SA400 Command)
    Software development process
    CSS display样式
    CSS行高line-height解释
    CS和CS3知识点
    HTML图片<img>标签空白解决方法
    CS清除浮动
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/12933396.html
Copyright © 2011-2022 走看看