传送门

Description

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Now your job is to find the total Hamming distance between all pairs of the given numbers.

Example:

Input: 4, 14, 2

Output: 6

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

Note:

  1. Elements of the given array are in the range of 0 to 10^9
  2. Length of the array will not exceed 10^4.

思路

题意:给定一个数组,其中两两配对,求出所有配对数的汉明距离。

题解:我们知道,汉明距离是两个数其二进制位上不同的位数,因此,对于32位数,遍历二进制位,统计每个数在第一个bit位有多少个数是1,有多少个数是0,然后统计第二个bit位,以此类推。

class Solution {
public:
//59ms
int totalHammingDistance(vector<int>& nums) {
int res = 0,len = nums.size();
for (int i = 0;i < 32;i++){
int cnt = 0;
for (int j = 0;j < len;j++){
cnt += (nums[j] >> j) & 1;
}
res += (len - cnt) * cnt;
}
return res;
}
};

  

最新文章

  1. SQL Server求解连续操作(登录)数量(次数)最大的记录(用户)问题
  2. SWFUpload 2.5.0版 官方说明文档 中文翻译版
  3. JQuery仿淘宝商家后台管理 之 管理添加分类
  4. linux which 查看可执行文件的位置
  5. 【转载】MySQL被慢sql hang住了,用shell脚本快速清除不断增长的慢sql的办法
  6. 玩转CSLA.NET小技巧系列二:使用WCF无法上传附件,提示413 Entity Too Large
  7. 图论(网络流):[HNOI 2013]切糕
  8. jQuery中事件的学习
  9. ansible 学习与实践
  10. iOS工程上传AppStore时遇到的问题“ERROR ITMS-90046”解析
  11. ContentProvider中的数据生成时机
  12. 上海投行需要一大群JAVA,C++,C#,UNIX.走过路过不要错过!过完年想换工作看过来初级资深都有 - V2EX
  13. 在WPF中使用PlaneProjection模拟动态3D效果
  14. Eclipse rap 富客户端开发总结(6) : 如何发布rap到tomcat
  15. 从实践的角度理解cookie的几个属性
  16. Spark算子篇 --Spark算子之aggregateByKey详解
  17. Linux内存管理专题
  18. IDEA适合的插件
  19. CFRunLoop 源码学习笔记(CF-1151.16)
  20. 大型运输行业实战_day01_2_需求文档

热门文章

  1. utf-8 bom头问题 thinkphp 报错 Namespace declaration statement has to be the very first statement in the script
  2. 什么是http协议??
  3. 2019 Multi-University Training Contest 2 - 1009 - 回文自动机
  4. RMQ 的入门 hdu1806
  5. struts2导入多个xml引入报错&lt;include&gt;
  6. OC学习--面向对象的个人理解
  7. js 一个不得不注意的浏览器兼容性问题 进制转换
  8. 构建LNMP+memcached服务
  9. Linux ssh内置sftp配置说明
  10. ARM平台常用性能测试方法