返回介绍

solution / 0400-0499 / 0477.Total Hamming Distance / README_EN

发布于 2024-06-17 01:04:00 字数 2977 浏览 0 评论 0 收藏 0

477. Total Hamming Distance

中文文档

Description

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 <= 104
  • 0 <= nums[i] <= 109
  • The answer for the given input will fit in a 32-bit integer.

Solutions

Solution 1

class Solution:
  def totalHammingDistance(self, nums: List[int]) -> int:
    ans = 0
    for i in range(31):
      a = b = 0
      for v in nums:
        t = (v >> i) & 1
        if t:
          a += 1
        else:
          b += 1
      ans += a * b
    return ans
class Solution {
  public int totalHammingDistance(int[] nums) {
    int ans = 0;
    for (int i = 0; i < 31; ++i) {
      int a = 0, b = 0;
      for (int v : nums) {
        int t = (v >> i) & 1;
        a += t;
        b += t ^ 1;
      }
      ans += a * b;
    }
    return ans;
  }
}
class Solution {
public:
  int totalHammingDistance(vector<int>& nums) {
    int ans = 0;
    for (int i = 0; i < 31; ++i) {
      int a = 0, b = 0;
      for (int& v : nums) {
        int t = (v >> i) & 1;
        a += t;
        b += t ^ 1;
      }
      ans += a * b;
    }
    return ans;
  }
};
func totalHammingDistance(nums []int) int {
  ans := 0
  for i := 0; i < 31; i++ {
    a, b := 0, 0
    for _, v := range nums {
      t := (v >> i) & 1
      a += t
      b += t ^ 1
    }
    ans += a * b
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文