zoukankan      html  css  js  c++  java
  • 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 ≤ x, y < 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.

    分析

    "corresponding bits are different"即"异或"运算,Java中"异或运算符"的符号为^
    (例:a的值是15,转换成二进制为1111;b的值是2,转换成二进制为0010。则a^b的结果为1101,即13。)
    此题可转化为:求x异或y的结果的二进制表达式中'1'的个数

    解答

    解法1:(我)遍历二进制字符串(12ms)

    将x异或y的结果转化为二进制字符串,遍历所有字符,求'1'的个数

    public class Solution {
        public int hammingDistance(int x, int y){
            String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
            int count = 0;
            for (int i = 0; i < str.length(); i++){
                if (str.charAt(i) == '1'){
                    count++;
                }
            }
            return count;
        }
    }
    


    解法2:求二进制字符串差值(18ms)

    将x异或y的结果转化为二进制字符串,将其中所有"1"替换为""(空字符串),求替换前后字符串长度差值

    public class Solution {
        public int hammingDistance(int x, int y){
            String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
            String str2 = str.replaceAll("1","");
            return str.length() - str2.length();
        }
    }
    

    ###解法3:使用系统内置函数Integer.bitCount()(24ms) Integer.bitCount() 返回指定int值的二进制补码表示形式的1位的数量。例:Integer.bitCount(5) = 2,因为5的二进制补码表示为101,其中'1'的个数为2 ``` public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } } ```
    ###解法4:位运算(>>, &)(11ms√) 计算xor & 1,若xor末位为1,结果为1;若xor末位为0,结果为0。将结果记入count。再将xor右移1位。重复上述过程,直到xor右移到尽头(xor == 0) 0101 ---> 010 ---> 01 ---> 0 ``` public class Solution { public int hammingDistance(int x, int y){ int xor = x ^ y; int count = 0; while (xor != 0){ count += xor & 1; xor >>= 1; } return count; } } ```
  • 相关阅读:
    2020年“3D视觉工坊”视频号最受欢迎视频 Top 10!
    缓存一致性解决方案杂谈
    Mybatis的@Param注解在多参数时候不写,可以正确执行。
    Redis设计与实现之简单动态字符串
    YApi mac上部署
    拖拽方式生成Vue用户界面
    终于可以愉快的撸Java异步代码了!
    Windows 取证之ShellBags
    初识Fastjson漏洞(环境搭建及漏洞复现)
    mongo-express 远程代码执行漏洞分析
  • 原文地址:https://www.cnblogs.com/xuehaoyue/p/6412242.html
Copyright © 2011-2022 走看看