Leetcode - 461. Hamming Distance n&=(n-1) (C++)
2024-08-28 22:37:05
1. 题目链接:https://leetcode.com/problems/hamming-distance/description/
2.思路
常规做法做完看到评论区一个非常有意思的做法。用了n&=(n-1),这个地方的意思是,将最右边的1变成0。比方说:
最简单的例子:
原数字: 101011
n-1: 101010
n&(n-1):101011&101010=101010
再看另一个例子:
原数字:10100
n-1: 10011
n&(n-1):10100&10011 = 10000
最后一个极端情况:
原数字:10000
n-1:01111
n&(n-1):10000&01111=00000
3.代码
(1)评论区的解法
class Solution {
public:
int hammingDistance(int x, int y) {
int n = x^y, hd = 0;
while(n)
{
hd++;
n &= (n-1);
}
return hd;
}
};
(2)常规解法
class Solution {
public:
int hammingDistance(int x, int y) {
int n = x^y, hd = 0;
while(n)
{
hd += (n % 2);
n = n >> 1;
}
return hd;
}
};
最新文章
- 让你脱离google不能访问的烦恼
- Jade模板引擎(一)之Attributes
- meta http-equiv='refresh' 解读
- 调用手机话费充值API的SDK编写思路
- org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER
- Decomposing and Redistributing the Statement Method
- Can't connect to local MySQL server through socket 问题解决
- (转载)shell变量基础—shell自定义变量
- getting start with storm 翻译 第八章 part-2
- 基于Qt的图像采集系统
- 在Vue中使用样式
- ARM的编程模式
- [js] 渲染树构建、布局及绘制
- switch选择结构
- AI模型训练/算法评估 测试员
- EasyUI 添加一行的时候 行号出现负数的解决方案
- centos7 更新源 安装ifconfig
- MongoDB排序记录
- linkText()的用法
- python16_day18【Django_Form表单、分页】
热门文章
- SQL SERVER 对权限的授予GRANT、拒绝DENY、收回REVOKE
- oracle database 9i/10g/11g 编程艺术 源代码下载
- Xcode 之 Debug 和 Release 模式切换方式 - iOS
- Linux系统中的vi/vim指令【详解】
- rails应用中各数据平台的对接
- pip快速git项目安装
- F. Make It Connected
- [Python3.X]python 实现斐波那契数列
- CF 810 D. Glad to see you!
- angular ng-bind-html $sce.trustAsHtml