LeetCode Problems: 461. Hamming Distance

題目資訊

  • 名稱:Hamming Distance
  • 分類:Algorithms
  • 編號:461
  • 難度:Easy
  • 標籤:Bit Manipulation
  • 網址:https://leetcode.com/problems/hamming-distance

題目描述

原文

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

Given two integers x and y, calculate the Hamming distance.

Note: 0 ≤ x, y < 231.

Example:

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.

中譯

漢明距離是計算兩個整數之間,相對應位置的位元有幾個不同。

給定兩個整個 xy,計算漢明距離。

注意:

0 ≤ x, y < 231.

範例:

輸入:x = 1, y = 4

輸出:2

解釋:
1	(0 0 0 1)
4	(0 1 0 0)
       ↑   ↑
       
上方的箭頭所指的位置就是位元不同。

參考解法

思路

這題是大專院校幾乎都教過的東西。

先 x XOR y,篩出不同的 bits,然後計算有多少個 bit 不同。

C++

class Solution {
public:
    int hammingDistance(int x, int y) {
        auto distance = 0;
        auto diff = x ^ y;
        
        while (diff != 0) {
            ++distance;
            diff &= diff - 1;
        }

        return distance;
    }
};

後記

有更快速的 bit manipulation 實作方法,可以參考 LeetCode 上其他人的 Solutions。

標籤 :

相關文章

Unity 5 AssetBundle 基礎

前言 一直以來,Unity 的 AssetBundle 機制與不透明的資訊一直為人所詬病(社群論壇有些批評,例如 asset 序列化管理架構、機制本身就不良,來源就不附上了),以往

更多

LeetCode Problems: 561. Array Partition I

題目資訊 名稱:Array Partition I 分類:Algorithms 編號:561 難度:Easy 標籤:Array 網址:https://leetcode.co

更多

LeetCode Problems: 1. Two Sum

題目資訊 名稱:Two Sum 分類:Algorithms 編號:1 難度:Easy 標籤:Array, Hash Table 網址:https://leetcode.com/

更多