LeetCode | 477. Total Hamming Distance

news/2024/10/23 9:33:41/

题目

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

Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.

Example 1:

Input: nums = [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).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

Example 2:

Input: nums = [4,14,4]
Output: 4

Constraints:

1 <= nums.length <= 10^4
0 <= nums[i] <= 10^9
The answer for the given input will fit in a 32-bit integer.

代码

class Solution {
public:int totalHammingDistance(vector<int>& nums) {if(nums.size()<=1)return 0;int dist = 0;for(int j = 0; j<32; j++){int bitnum = 0;for(int i = 0; i<nums.size(); i++){bitnum += (nums[i]>>j) & 1;}dist += bitnum * (nums.size()-bitnum);}return dist;}
};

http://www.ppmy.cn/news/535623.html

相关文章

【博客477】prometheus-----数值数据编码(varint与zigzag)

prometheus-----数据编码(varint与zigzag) prometheus对数值数据进行编码时&#xff0c;使用到了varint与zigzag varint与zigzag编码方法在protobuf中也被使用 prometheus encoding代码&#xff1a; https://github.com/prometheus/prometheus/blob/main/tsdb/encoding/encodi…

​LeetCode刷题实战477:汉明距离总和

算法的重要性&#xff0c;我就不多说了吧&#xff0c;想去大厂&#xff0c;就必须要经过基础知识和业务逻辑面试算法面试。所以&#xff0c;为了提高大家的算法能力&#xff0c;这个公众号后续每天带大家做一道算法题&#xff0c;题目就从LeetCode上面选 &#xff01; 今天和大…

LeetCode 算法 每日一题 477.汉明距离总和

10.正则表达式匹配 题目描述 两个整数的汉明距离指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中&#xff0c;任意两个数之间汉明距离的总和。 示例1 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中&#xff0c;4表示为0100&#xff0c;14表示为1110&#xff0…

奇舞周刊 477 期:一文弄懂 React ref 原理

记得点击文章末尾的“ 阅读原文 ”查看哟~ 下面先一起看下本期周刊 摘要 吧~ 奇舞推荐 ■ ■ ■ 一文弄懂 React ref 原理 对于 Ref 理解与使用&#xff0c;一些读者可能还停留在用 ref 获取真实 DOM 元素和获取类组件实例层面上 其实 ref 除了这两项常用功能之外&#xff0c;还…

Java实现 LeetCode 477 汉明距离总和

477. 汉明距离总和 两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中&#xff0c;任意两个数之间汉明距离的总和。 示例: 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中&#xff0c;4表示为0100&#xff0c;14表示为1110&#xff0c;2表…

leetcode 477.汉明距离总和

每日一题 昨天做了道相似的汉明距离详见leetcode461&#xff0c;今天又看见类似的题目准备重拳出击&#xff01; 博主技术有限…于是直接暴力 class Solution {public int totalHammingDistance(int[] nums) {int sum 0;int total 0;for(int i 0;i < nums.length;i){for…

leetcode 477 汉明距离总和(位运算、排列组合)

题目描述&#xff1a; 两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中&#xff0c;任意两个数之间汉明距离的总和。 示例: 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中&#xff0c;4表示为0100&#xff0c;14表示为1110&#xff0c;…

【CodeForces】CodeForces Round #477 (Div. 1 + Div. 2) 题解

【比赛链接】 Div. 1Div. 2 【题解链接】 点击打开链接 【Div.2 A】Mind the Gap 【思路要点】 从小到大枚举答案&#xff0c;检查合法性。时间复杂度\(O(Ans*N)\)。 【代码】 #include<bits/stdc.h> using namespace std; const int MAXN 100005; template <typena…