1、問題分析
題目鏈接:https://leetcode-cn.com/problems/hamming-distance/
本質上就是一個進制轉換問題。代碼我已經進行了詳細的註釋,理解應該沒有問題,讀者可以作爲參考,如果看不懂(可以多看幾遍),歡迎留言哦!我看到會解答一下。
2、問題解決
筆者以C++
方式解決。
#include "iostream"
using namespace std;
#include "algorithm"
#include "vector"
#include "queue"
#include "set"
#include "map"
#include "string"
#include "stack"
class Solution {
public:
int hammingDistance(int x, int y) {
// 定義 1 的個數
int num = 0;
// 獲取漢明距離 10 進製表示
int result = x ^y;
// 將 10進制 轉化成 2進制
while (result > 0) {
// 遇到 1 則個數 +1
if (result % 2 == 1) {
num++;
}
// 不斷縮小 result 值
result /= 2;
}
// 返回結果
return num;
}
};
int main() {
Solution *pSolution = new Solution;
int i = pSolution->hammingDistance(1, 4);
cout << i << endl;
system("pause");
return 0;
}
運行結果
有點菜,有時間再優化一下。
3、總結
難得有時間刷一波LeetCode
, 這次做一個系統的記錄,等以後複習的時候可以有章可循,同時也期待各位讀者給出的建議。算法真的是一個照妖鏡,原來感覺自己也還行吧,但是算法分分鐘教你做人。前人栽樹,後人乘涼。在學習算法的過程中,看了前輩的成果,受益匪淺。
感謝各位前輩的辛勤付出,讓我們少走了很多的彎路!
哪怕只有一個人從我的博客受益,我也知足了。
點個贊再走唄!歡迎留言哦!