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

二、我的思路

首先想到用位运算。

先把x和y异或(^),记作xor,里面是1的表示x与y不同的位,是0的表示相同的位。然后统计这个数字的二进制里面有多少个1就行了~

统计的时候每次把xor和1做与(&)运算,加到count里。因为规定了它们的最大值,所以循环最多32次,统计32位的情况。

代码:

class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        for(int i = 0; i < 32; i ++){
            count += xor & 1;
            xor = xor >> 1;
        }
        return count;
    }
}


三、别人的淫奇技巧

1. 用我没见过的函数……

public class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

2. 方法类似,短小精悍。。

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

3. 这个有点高端的样子

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }
};
看不懂啊,这是什么…引用大神的解答:

@jonvasquez1 Considering this example. Let's say n = 10101, and dist = 0 asccording to above code of @pengr7.

  • Before we go into the while loop. n = 10101, dist = 0
  • Loop 1.  dist = 1, n =10101 & 10100 = 10100
  • Loop 2.  dist = 2, n =10100 & 10011 = 10000
  • Loop 3.  dist = 3, n =10000 & (0)1111 = 0
  • Loop ends. dist = 3

The change of n :

  • 10101
  • 10100
  • 10000
  • 00000

Conclusion: n & (n-1) converts the right most 1 to 0 .
This is the key idea solving the problem. By counting how many times we can perform this operation, we know how many 1 exists in the binary representation of n

大概意思就是,n&(n-1)会把二进制最右边的1变成0。然后有几个1就能变成几个不为0的值。简直6666~差距吖

四、知识点

位运算。

参考博客:http://blog.youkuaiyun.com/xiaochunyong/article/details/7748713


五、碎碎念

对Java的位运算符不是特别熟悉。。继续加油~

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.9

TensorFlow-v2.9

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

比对请使用chromap”chromap Fast alignment and preprocessing of chromatin profiles Usage: chromap [OPTION...] -v, --version Print version -h, --help Print help Indexing options: -i, --build-index Build index --min-frag-length INT Min fragment length for choosing k and w automatically [30] -k, --kmer INT Kmer length [17] -w, --window INT Window size [7] Mapping options: --preset STR Preset parameters for mapping reads (always applied before other options) [] atac: mapping ATAC-seq/scATAC-seq reads chip: mapping ChIP-seq reads hic: mapping Hi-C reads --split-alignment Allow split alignments -e, --error-threshold INT Max # errors allowed to map a read [8] -s, --min-num-seeds INT Min # seeds to try to map a read [2] -f, --max-seed-frequencies INT[,INT] Max seed frequencies for a seed to be selected [500,1000] -l, --max-insert-size INT Max insert size, only for paired-end read mapping [1000] -q, --MAPQ-threshold INT Min MAPQ in range [0, 60] for mappings to be output [30] --min-read-length INT Min read length [30] --trim-adapters Try to trim adapters on 3' --remove-pcr-duplicates Remove PCR duplicates --remove-pcr-duplicates-at-bulk-level Remove PCR duplicates at bulk level for single cell data --remove-pcr-duplicates-at-cell-level Remove PCR duplicates at cell level for single cell data --Tn5-shift Perform Tn5 shift --low-mem Use low memory mode --bc-error-threshold INT Max Hamming distance allowed to correct a barcode [1] --bc-probability-threshold FLT Min probability to correct a barcode [0.9] -t, --num-threads INT # threads for mapping [1] --frip-est-params STR coefficients used for frip est calculation, separated by semi-colons --turn-off-num-uniq-cache-slots turn off the output of number of cache slots in summary file Input options: -r, --ref FILE Reference file -x, --index FILE Index file -1, --read1 FILE Single-end read files or paired-end read files 1 -2, --read2 FILE Paired-end read files 2 -b, --barcode FILE Cell barcode files --barcode-whitelist FILE Cell barcode whitelist file --read-format STR Format for read files and barcode files ["r1:0:-1,bc:0:-1" as 10x Genomics single-end format] Output options: -o, --output FILE Output file --output-mappings-not-in-whitelist Output mappings with barcode not in the whitelist --chr-order FILE Custom chromosome order file. If not specified, the order of reference sequences will be used --BED Output mappings in BED/BEDPE format --TagAlign Output mappings in TagAlign/PairedTagAlign format --SAM Output mappings in SAM format --pairs Output mappings in pairs format (defined by 4DN for HiC data) --pairs-natural-chr-order FILE Custom chromosome order file for pairs flipping. If not specified, the custom chromosome order will be used --barcode-translate FILE Convert barcode to the specified sequences during output --summary FILE Summarize the mapping statistics at bulk or barcode level (Hic) [scb3201@ln137%bscc-a6 Hic]$ “
12-06
【最优潮流】直流最优潮流(OPF)课设(Matlab代码实现)内容概要:本文档主要围绕“直流最优潮流(OPF)课设”的Matlab代码实现展开,属于电力系统优化领域的教学与科研实践内容。文档介绍了通过Matlab进行电力系统最优潮流计算的基本原理与编程实现方法,重点聚焦于直流最优潮流模型的构建与求解过程,适用于课程设计或科研入门实践。文中提及使用YALMIP等优化工具包进行建模,并提供了相关资源下载链接,便于读者复现与学习。此外,文档还列举了大量与电力系统、智能优化算法、机器学习、路径规划等相关的Matlab仿真案例,体现出其服务于科研仿真辅导的综合性平台性质。; 适合人群:电气工程、自动化、电力系统及相关专业的本科生、研究生,以及从事电力系统优化、智能算法应用研究的科研人员。; 使用场景及目标:①掌握直流最优潮流的基本原理与Matlab实现方法;②完成课程设计或科研项目中的电力系统优化任务;③借助提供的丰富案例资源,拓展在智能优化、状态估计、微电网调度等方向的研究思路与技术手段。; 阅读建议:建议读者结合文档中提供的网盘资源,下载完整代码与工具包,边学习理论边动手实践。重点关注YALMIP工具的使用方法,并通过复现文中提到的多个案例,加深对电力系统优化问题建模与求解的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值