当前位置:网站首页>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;
}
}
边栏推荐
- 【博主推荐】C# Winform定时发送邮箱(附源码)
- 【博主推荐】asp.net WebService 后台数据API JSON(附源码)
- C language string function summary
- [recommended by bloggers] background management system of SSM framework (with source code)
- 【博主推荐】SSM框架的后台管理系统(附源码)
- CSDN markdown editor
- 【博主推荐】C#MVC列表实现增删改查导入导出曲线功能(附源码)
- MySQL27-索引优化与查询优化
- Global and Chinese market for intravenous catheter sets and accessories 2022-2028: Research Report on technology, participants, trends, market size and share
- Baidu Encyclopedia data crawling and content classification and recognition
猜你喜欢

Mysql30 transaction Basics

Mysql36 database backup and recovery

Solution: log4j:warn please initialize the log4j system properly
![[reading notes] rewards efficient and privacy preserving federated deep learning](/img/c3/5e88277b5024885d5ceeaa0de14b27.jpg)
[reading notes] rewards efficient and privacy preserving federated deep learning

Mysql21 user and permission management

Installation and use of MySQL under MySQL 19 Linux

MySQL23-存儲引擎

A brief introduction to the microservice technology stack, the introduction and use of Eureka and ribbon

Windows cannot start the MySQL service (located on the local computer) error 1067 the process terminated unexpectedly

【博主推荐】SSM框架的后台管理系统(附源码)
随机推荐
MySQL主從複制、讀寫分離
【博主推荐】C#MVC列表实现增删改查导入导出曲线功能(附源码)
Global and Chinese markets for aprotic solvents 2022-2028: Research Report on technology, participants, trends, market size and share
Install mysql5.5 and mysql8.0 under windows at the same time
MySQL23-存储引擎
MySQL29-数据库其它调优策略
MySQL24-索引的数据结构
Nanny hand-in-hand teaches you to write Gobang in C language
MySQL27-索引優化與查詢優化
Breadth first search rotten orange
Mysql27 index optimization and query optimization
Mysql26 use of performance analysis tools
Redis的基础使用
A brief introduction to the microservice technology stack, the introduction and use of Eureka and ribbon
Global and Chinese market of thermal mixers 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL18-MySQL8其它新特性
CSDN问答标签技能树(五) —— 云原生技能树
There are three iPhone se 2022 models in the Eurasian Economic Commission database
C language string function summary
Mysql30 transaction Basics