[原题链接](https://leetcode.com/problems/hamming-distance/description/)
复制代码
我的源代码
class Solution
{
public static int hammingDistance(int x, int y)
{
int hammingDistance = 0;
Stack<Integer> xToBinary = transfer(x);
Stack<Integer> yToBinary = transfer(y);
int maxNumber = max(x,y);
while(xToBinary.size() != 0)
{
if (maxNumber == x && xToBinary.size() > yToBinary.size())
{
if (xToBinary.pop() == 1) hammingDistance++;
}
else if (maxNumber == y && yToBinary.size() > xToBinary.size())
{
if (yToBinary.pop() == 1) hammingDistance++;
}
else if (xToBinary.pop() != yToBinary.pop()) hammingDistance++;
}
return hammingDistance;
}
public static Stack<Integer> transfer(int integer)
{
Stack<Integer> binary = new Stack<Integer>();
if(integer == 0) binary.push(0);
while(integer != 0)
{
binary.push(integer%2);
integer /= 2;
}
return binary;
}
public static int max(int x,int y)
{
if(x > y) return x;
else return y;
}
}
复制代码
- 思路
使用stack()
LeetCode优秀题解
^
→ 异或
1.十进制数去异或:十进制数转为二进制数→对应取异或得到一个二进制数→转化为十进制数
2.bitCount