https://leetcode.com/problems/hamming-distance/description/
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.
想速度摸一題Easy題睡覺的风范,結(jié)果還是調(diào)試了幾次椿访。。
第一加酵,比較的順序是從前往后還是從后往前要想清楚哭当。第二,charAt又忘記加單引號了' '陋葡。
public int hammingDistance(int x, int y) {
String xs = Integer.toBinaryString(x);
String ys = Integer.toBinaryString(y);
int count = 0;
for (int i = 0 ; i < Math.min(xs.length(), ys.length()); i++) {
if (xs.charAt(xs.length() - 1- i) != ys.charAt(ys.length()-1 - i)) {
count++;
}
}
String targetS = xs.length() > ys.length() ? xs : ys;
for (int j = 0 ; j < targetS.length() - Math.min(xs.length() , ys.length()); j++) {
if (targetS.charAt(j) != '0') {
count++;
}
}
return count;
}
1 line solution
https://discuss.leetcode.com/topic/72093/java-1-line-solution-d:
What does come to your mind first when you see this sentence "corresponding bits are different"? Yes, XOR! Also, do not forget there is a decent function Java provided: Integer.bitCount() ~~~
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
3 line solution腐缤,值得看看位運算
http://blog.csdn.net/xiaochunyong/article/details/7748713
public int hammingDistance(int x, int y) {
int xor = x ^ y, count = 0;
for (int i=0;i<32;i++) count += (xor >> i) & 1;
return count;
}
x ^ y的意思是按位異或肛响,也就是說把它們不同的bit變?yōu)?,相同的變成0特笋。然后每次右移1位,與1相與猎物,計算1的個數(shù)。用到了異或淘讥,右移和與運算堤如,不錯的訓(xùn)練。