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;
}
};

  

最新文章

  1. 让你脱离google不能访问的烦恼
  2. Jade模板引擎(一)之Attributes
  3. meta http-equiv='refresh' 解读
  4. 调用手机话费充值API的SDK编写思路
  5. org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER
  6. Decomposing and Redistributing the Statement Method
  7. Can't connect to local MySQL server through socket 问题解决
  8. (转载)shell变量基础—shell自定义变量
  9. getting start with storm 翻译 第八章 part-2
  10. 基于Qt的图像采集系统
  11. 在Vue中使用样式
  12. ARM的编程模式
  13. [js] 渲染树构建、布局及绘制
  14. switch选择结构
  15. AI模型训练/算法评估 测试员
  16. EasyUI 添加一行的时候 行号出现负数的解决方案
  17. centos7 更新源 安装ifconfig
  18. MongoDB排序记录
  19. linkText()的用法
  20. python16_day18【Django_Form表单、分页】

热门文章

  1. SQL SERVER 对权限的授予GRANT、拒绝DENY、收回REVOKE
  2. oracle database 9i/10g/11g 编程艺术 源代码下载
  3. Xcode 之 Debug 和 Release 模式切换方式 - iOS
  4. Linux系统中的vi/vim指令【详解】
  5. rails应用中各数据平台的对接
  6. pip快速git项目安装
  7. F. Make It Connected
  8. [Python3.X]python 实现斐波那契数列
  9. CF 810 D. Glad to see you!
  10. angular ng-bind-html $sce.trustAsHtml