当前位置:网站首页>LeetCode #461 汉明距离
LeetCode #461 汉明距离
2022-07-06 09:13:00 【三笠·阿卡曼】
题目
两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。
给你两个整数 x 和 y,计算并返回它们之间的汉明距离。
示例

最佳代码
package com.vleus.algorithm.bit_operator;
/** * @author vleus * @date 2021年08月03日 22:35 */
public class HammingDistance {
//方法一:异或:调库统计1的个数
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
//方法二:自定义实现统计1的个数,逐位右移
public int hammingDistance2(int x, int y) {
int xor = x ^ y; //得到异或结果
int count = 0; //保存当前1的个数
//逐位右移,直到结果为0
while (xor != 0) {
//如果最后一位为1,count++
if ((xor & 1) == 1) {
count++;
}
xor >>=1; //右移1位
}
return count;
}
public int hammingDistance3(int x, int y) {
int xor = x ^ y; //得到异或结果
int count = 0; //保存当前1的个数
//快速位移,每次寻找当前最右面的一个1,直接消去
while (xor != 0) {
xor = xor & xor - 1;
count++;
}
return count;
}
}
边栏推荐
- Invalid default value for 'create appears when importing SQL_ Time 'error reporting solution
- MySQL21-用户与权限管理
- npm一个错误 npm ERR code ENOENT npm ERR syscall open
- Mysql34 other database logs
- Mysql32 lock
- API learning of OpenGL (2004) gl_ TEXTURE_ MIN_ FILTER GL_ TEXTURE_ MAG_ FILTER
- CSDN question and answer module Title Recommendation task (II) -- effect optimization
- Development of C language standard
- IDEA 导入导出 settings 设置文件
- Unicode decodeerror: 'UTF-8' codec can't decode byte 0xd0 in position 0 successfully resolved
猜你喜欢
随机推荐
MySQL27-索引優化與查詢優化
windows无法启动MYSQL服务(位于本地计算机)错误1067进程意外终止
Isn't there anyone who doesn't know how to write mine sweeping games in C language
MySQL21-用户与权限管理
MySQL transaction log
Pytoch LSTM implementation process (visual version)
frp内网穿透那些事
February 13, 2022 - Maximum subarray and
A brief introduction to the microservice technology stack, the introduction and use of Eureka and ribbon
导入 SQL 时出现 Invalid default value for ‘create_time‘ 报错解决方法
MySQL 29 other database tuning strategies
API learning of OpenGL (2004) gl_ TEXTURE_ MIN_ FILTER GL_ TEXTURE_ MAG_ FILTER
Navicat 導出錶生成PDM文件
MySQL29-数据库其它调优策略
Mysql21 - gestion des utilisateurs et des droits
MySQL30-事务基础知识
Mysql33 multi version concurrency control
CSDN question and answer tag skill tree (I) -- Construction of basic framework
csdn-Markdown编辑器
Invalid default value for 'create appears when importing SQL_ Time 'error reporting solution








