LeetCode - 461. Hamming Distance


題目意思:
  這題主要是給予兩個Integer,再2進制表達下,有幾個bit不一樣(同位置)

解決方式:
  先用XOR做運算,C++的語法為" ^ ",當兩個數字bit不相同,該bit做XOR後輸出為1,以Integer長度為中止條件,計算出現幾次1即為答案。

 
  1. class Solution {
  2. public:
  3. int hammingDistance(int x, int y) {
  4. int c = x^y;
  5. int count = 0;
  6. while(c>0)
  7. {
  8. if(c%2 == 1)
  9. {
  10. count++;
  11. }
  12. c/=2;
  13. }
  14. return count;
  15. }
  16. };

留言