LeetCode之Hamming Distance
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Hamming Distance
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、題目
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 = 4Output: 2Explanation: 1 (0 0 0 1) 4 (0 1 0 0)↑ ↑The above arrows point to positions where the corresponding bits are different.題意:
給定兩個整數x,y,計算x和y的漢明距離。漢明距離是指x、y的二進制表示中,相同位置上數字不相同的所有情況數。
2、代碼實現
public class Solution {public int hammingDistance(int x, int y) {int notSame = x ^ y;int count = 0;while (notSame != 0) {if (notSame % 2 == 1)++count;notSame /= 2;}return count;}
} 注意記得用 異或0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 0 ^ 0 = 0 然后就是我們平時10進制的話,每次去掉末尾的數字是 / 10,二進制的話就是/2,切記。
總結
以上是生活随笔為你收集整理的LeetCode之Hamming Distance的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode之Reverse Str
- 下一篇: LeetCode之Keyboard Ro