LeetCode 力扣477. 汉明距离总和 最易理解解法

news/2024/10/23 5:43:54/

两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。
给你一个整数数组 nums,请你计算并返回 nums 中任意两个数之间 汉明距离的总和 。
在这里插入图片描述
在这里插入图片描述

class Solution {public int totalHammingDistance(int[] nums) {int ans = 0;//遍历32位for (int i = 0; i < 32; i++) {//判断每一位上有几个1,几个0,1的个数乘以0的个数就是距离总和//a表示1的个数,b表示0的个数int a = 0;int b = 0;//遍历每一位上有几个0,几个1for(int num : nums) {//右移int tmp = num >> i;//判断是0还是1,0 & 1 = 0 ,1 & 1 = 1if((tmp & 1) == 1){a++;}else{b++;}}ans += a * b;}return ans;}
}

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

相关文章

LeetCode-473

火柴拼正方形 你将得到一个整数数组 matchsticks &#xff0c;其中 matchsticks[i] 是第 i 个火柴棒的长度。你要用 所有的火柴棍 拼成一个正方形。你 不能折断 任何一根火柴棒&#xff0c;但你可以把它们连在一起&#xff0c;而且每根火柴棒必须 使用一次 。如果你能使这个正…

leetcode 477. Total Hamming Distance | 477. 汉明距离总和

题目 https://leetcode.com/problems/total-hamming-distance/ 题解 class Solution {public int totalHammingDistance(int[] nums) {int N nums.length;int[] count new int[32];for (int n : nums) {for (int i 0; i < 32; i) {count[i] (n >> i) & 1;}…

477-82(236、61、47、74、240、93)

236. 二叉树的最近公共祖先 class Solution { public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if (root p || root q || root nullptr) return root;TreeNode* left lowestCommonAncestor(root->left, p, q);TreeNode* right l…

LeetCode 477 汉明距离总和

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

477. 汉明距离总和(中等,位运算)

題目&#xff1a; 分析1&#xff0c;统计每一位的1个数&#xff1a;T了。 class Solution:def totalHammingDistance(self, nums: List[int]) -> int:a len(nums) # 总个数if len(nums)0 :return 0a2 max(nums)c [0 for i in range(0,a2)]for i in nums:if i0:continues…

LeetCode笔记:477. Total Hamming Distance

问题&#xff1a; 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:…

LeetCode 47

这个题是对上一个题的变形&#xff0c;变化的条件是数组里面可以出现相同的元素&#xff0c;这样确实加大了难度。不过在上个题的基础上我们可以把精力主要放在怎么处理重复的数字。如果没有记错&#xff0c;我们之前的一道题也是类似情况&#xff0c;我看了一下是 LeetCode 40…

4.17 一

现有一网络拓扑图如上 要求&#xff1a;①AR1 GE000口用接口DHCP分配IP ②AR1001口用全局DHCP分配IP ③各PC间互通 思路&#xff1a; ①想给PC1、2分配IP需要进入充当DHCP服务器的AR1的000端口配置IP&#xff0c;启用DHCP协议&#xff0c;配置接口地址池并调用。无需配置IP和…