477. Total Hamming Distance
来源:互联网 发布:淘宝代理加盟的骗局 编辑:程序博客网 时间:2024/06/07 03:13
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, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing 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:
- Elements of the given array are in the range of
0
to10^9
- Length of the array will not exceed
10^4
.
Subscribe to see which companies asked this question.
进化过程:
public class _477 {public int totalHammingDistance(int[] nums) {int[] zero = new int[32];int[] one = new int[32];int len = nums.length;for (int i = 0; i < 32; ++i)zero[i] = len;for (int n : nums) {int i = 0;while (n != 0) {int cur = n % 2;n /= 2;if (cur == 1) {zero[i] -= 1;one[i] += 1;}i += 1;}}int re = 0;for (int i = 0; i < 32; ++i)re += zero[i] * one[i];return re;}}
public class _477plus {public int totalHammingDistance(int[] nums) {int[] one = new int[32];int len = nums.length;for (int n : nums) {int i = 0;while (n != 0) {if (n % 2 == 1)one[i] += 1;i += 1;n /= 2;}}int re = 0;for (int i = 0; i < 32; ++i)re = re + one[i] * (len - one[i]);return re;}}
public class _477plusplus {public int totalHammingDistance(int[] nums) {int len = nums.length;int re = 0;for (int i = 0; i < 32; ++i) {int one = 0;for (int n : nums)one += (n >> i) & 1;re += one * (len - one);}return re;}}
阅读全文
0 0
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance**
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- 【Leetcode】477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- [leetcode] 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- XlistView的简单的使用
- 入门动画篇之UIView动画(二)-----浅谈CABasicAnimation基本使用方法
- jsonlib的测试使用
- glStencilFuncSeparate
- vue.js原生组件化开发(一)——组件开发基础
- 477. Total Hamming Distance
- 一、几个概念
- iOS
- composer 的常见使用
- 如何调用FindWindow API获取主窗体
- 不同版本(2.3-3.1)web.xml文件的schema头部声明
- iOS开发-平台使用TestFlight进行Beta测试
- 网络&加密刷题笔记-2
- java中 Process的使用