最近事情比較少,決定來刷個LeetCode來練練功吧!!

因為之前也沒做過這些

所以花了點時間了解了一下

決定重easy開始刷題吧~~~

以下

-----------

 

今天挑的題目是 461.  Hamming Distance

以下是題目:

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

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

Note:
0 <= x, y < (2)31次方

以下是範例:

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

 

題目主要是要你算Hamming Distance,這題還蠻簡單的(一次過關~~

相信大家知道Hamming Distance的算法

就是把2個十進位轉成2進位後

去比較2個數字間的差異

例如: 0001和0100的Hamming Distance是2

1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

只要同為元間數字是不一樣的,Hamming Distance就會加1

 

以下

-------

程式碼:

class Solution {
public:
    int hammingDistance(int x, int y) {
      vector <int> a(32,0);
      vector <int> b(32,0);
        int i,count=0;
/*
   先將x,y轉成2進位,並放入vector中
*/
         for(i=0;i<a.size();i++)
          {
            a[i]=x%2;
             b[i]=y%2;
             x=x/2;
             y=y/2;
          }

//再來比較a,b vector,不一樣的count就會+1
         for(i=0;i<a.size();i++)
          {
            if(a[i]!=b[i]){count++;}
            
          }
        return count;
    }
};

結束,收工,簡單吧~~

大家也來刷Leetcode吧!!

 

arrow
arrow

    kyo 發表在 痞客邦 留言(0) 人氣()