Skip to content

Latest commit

 

History

History
127 lines (87 loc) · 2.65 KB

hamming-distance.md

File metadata and controls

127 lines (87 loc) · 2.65 KB

461. Hamming Distance - 汉明距离

Tags - 题目标签

Description - 题目描述

EN:

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

Given two integers x and y, return the Hamming distance between them.

 

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

 

Constraints:

  • 0 <= x, y <= 231 - 1

ZH-CN:

两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。

给你两个整数 xy,计算并返回它们之间的汉明距离。

 

示例 1:

输入:x = 1, y = 4
输出:2
解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
上面的箭头指出了对应二进制位不同的位置。

示例 2:

输入:x = 3, y = 1
输出:1

 

提示:

  • 0 <= x, y <= 231 - 1

Link - 题目链接

LeetCode - LeetCode-CN

Latest Accepted Submissions - 最近一次 AC 的提交

Language Runtime Memory Submission Time
typescript 64 ms 42.5 MB 2023/07/23 13:15
function hammingDistance(x: number, y: number): number {
  let res = 0;

  while (x > 0 && y > 0) {
    const curX = x & 1;
    const curY = y & 1;
    if (curX !== curY) {
      res++;
    }
    x = x >> 1;
    y = y >> 1;
  }

  while (x > 0) {
    if (x & 1) {
      res++;
    }
    x = x >> 1;
  }

  while (y > 0) {
    if (y & 1) {
      res++;
    }
    y = y >> 1;
  }

  return res;
};

My Notes - 我的笔记

No notes