[C#][LeetCode][Easy] 461. Hamming Distance

心得:

剛開始看到題目的時候,突然發現我連Hamming Distance是什麼都不清楚,Google一下才知道,原來是把一數字轉成二進位,並依序比對是否相異,如101010與111010紅色標記的地方不一樣,則距離為一,有了起頭後就好解決了 !!

 

題目:

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.

答案:

public class Solution {
    public int HammingDistance(int x, int y) {
        int ans = 0;
        string num_1 = Convert.ToString(x, 2);
        string num_2 = Convert.ToString(y, 2);
        if ( num_1.Length != num_2.Length ){
            if ( num_1.Length > num_2.Length ){
                int diff = num_1.Length - num_2.Length;
                for ( int i = 0 ; i < diff ; i++){
                    num_2 = "0" + num_2;
                }
            }else{
                int diff = num_2.Length - num_1.Length;
                for ( int i = 0 ; i < diff ; i++){
                    num_1 = "0" + num_1;
                }
            }
        }
        for( int i = 0 ; i < num_1.Length; i++ ){
            if( num_1[i] != num_2[i] ){
                ans++;
            }
        }
        
        return ans;
    }
}

 

 

參考網站:

  1. Hamming distance
  2. [C#] 轉2進位 / 10進位 / 16進位

 

 

 



這裡的資訊對您有用嗎?歡迎斗內給我