[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的位运算符不是特别熟悉。。继续加油~

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

Dify

Dify

AI应用
Agent编排

Dify 是一款开源的大语言模型(LLM)应用开发平台,它结合了 后端即服务(Backend as a Service) 和LLMOps 的理念,让开发者能快速、高效地构建和部署生产级的生成式AI应用。 它提供了包含模型兼容支持、Prompt 编排界面、RAG 引擎、Agent 框架、工作流编排等核心技术栈,并且提供了易用的界面和API,让技术和非技术人员都能参与到AI应用的开发过程中

比对请使用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
MATLAB代码实现了一个基于多种智能优化算法优化RBF神经网络的回归预测模型,其核心是通过智能优化算法自动寻找最优的RBF扩展参数(spread),以提升预测精度。 1.主要功能 多算法优化RBF网络:使用多种智能优化算法优化RBF神经网络的核心参数spread。 回归预测:对输入特征进行回归预测,适用于连续值输出问题。 性能对比:对比不同优化算法在训练集和测试集上的预测性能,绘制适应度曲线、预测对比图、误差指标柱状图等。 2.算法步骤 数据准备:导入数据,随机打乱,划分训练集和测试集(默认7:3)。 数据归一化:使用mapminmax将输入和输出归一化到[0,1]区间。 标准RBF建模:使用固定spread=100建立基准RBF模型。 智能优化循环: 调用优化算法(从指定文件夹中读取算法文件)优化spread参数。 使用优化后的spread重新训练RBF网络。 评估预测结果,保存性能指标。 结果可视化: 绘制适应度曲线、训练集/测试集预测对比图。 绘制误差指标(MAE、RMSE、MAPE、MBE)柱状图。 十种智能优化算法分别是: GWO:灰狼算法 HBA:蜜獾算法 IAO:改进天鹰优化算法,改进①:Tent混沌映射种群初始化,改进②:自适应权重 MFO:飞蛾扑火算法 MPA:海洋捕食者算法 NGO:北方苍鹰算法 OOA:鱼鹰优化算法 RTH:红尾鹰算法 WOA:鲸鱼算法 ZOA:斑马算法
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值