LeetCode - 461. Hamming Distance
2016-03-07 11:18
483 查看
Description
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.Given two integers
xand
y, calculate the Hamming distance.
Note:
0 ≤
x,
y< 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.
Solution
除了最容易想到的暴力法,还可以用n与n-1按位与的方法python版:
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ xor = x ^ y count = 0 while (xor != 0): xor = xor & (xor - 1) count = count + 1 return count
cpp版:
class Solution { public: int hammingDistance(int x, int y) { int xor_diff = x ^ y; int count = 0; while (xor_diff != 0) { count++; xor_diff = xor_diff & (xor_diff-1); } return count; } };
Reference:
http://www.cnblogs.com/grandyang/p/6201215.html
相关文章推荐
- java thread programming
- Binlog_cache_size
- 世界领先的跨平台开发技术Qt Enterprise 5.6 新功能预览
- STM8S003F3控制LED
- 3. PSR-3 --- 日志接口
- 2. PSR-2 --- 代码风格指南
- iOS微信支付
- Android性能优化
- 110.View the Exhibit and examine the structure of the CUSTOMERS table.
- 使IE支持placeholder
- HTML5 data-* 自定义属性
- GeoJSON相关操作
- USB总线介绍
- MIS系统中的报表测试
- [置顶] 卡车图像分离车头、车厢、车轮
- 如何提取PDF文件中的部分页面内容
- MVVM框架
- DWR框架简介
- Adam学习之7代码kmer.scala完善(统计和SaveAsFile)
- JQuery中的id选择器含有特殊字符时,不能选中dom元素的解决方法