LeetCode之Hamming Distance
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Hamming Distance
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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.題意:
給定兩個(gè)整數(shù)x,y,計(jì)算x和y的漢明距離。漢明距離是指x、y的二進(jìn)制表示中,相同位置上數(shù)字不相同的所有情況數(shù)。
2、代碼實(shí)現(xiàn)
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 然后就是我們平時(shí)10進(jìn)制的話,每次去掉末尾的數(shù)字是 / 10,二進(jìn)制的話就是/2,切記。
總結(jié)
以上是生活随笔為你收集整理的LeetCode之Hamming Distance的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LeetCode之Reverse Str
- 下一篇: LeetCode之Keyboard Ro