Leetcode 461 Hamming Distance 自制答案
2017-04-21 19:34
561 查看
The Hamming distance between two integers is the number of positions at which the corresponding
bits are different.
Given two integers
calculate the Hamming distance.
Note:
0 ≤
231.
Example:
答案描述上来说,就是找出两个数的异或位的个数。
leetcode上有个别人写的一行代码,就是直接借助了Integer库的方法,当然我是想不到的啦。
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
自己写的算法在下面,就是进行位操作。
每次比较最后一位,然后对两组数进行右移操作,直到最大的那个数等于0为止。
public class Solution {
public int hammingDistance(int x, int y) {
int hamDistance = 0;
while((x>0)||(y>0)){
if((x&1)!=(y&1)){
hamDistance++;
}
x=x>>>1;
y=y>>>1;
}
return hamDistance;
}
}
bits are different.
Given two integers
xand
y,
calculate the Hamming distance.
Note:
0 ≤
x,
y<
231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
答案描述上来说,就是找出两个数的异或位的个数。
leetcode上有个别人写的一行代码,就是直接借助了Integer库的方法,当然我是想不到的啦。
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
自己写的算法在下面,就是进行位操作。
每次比较最后一位,然后对两组数进行右移操作,直到最大的那个数等于0为止。
public class Solution {
public int hammingDistance(int x, int y) {
int hamDistance = 0;
while((x>0)||(y>0)){
if((x&1)!=(y&1)){
hamDistance++;
}
x=x>>>1;
y=y>>>1;
}
return hamDistance;
}
}
相关文章推荐
- Leetcode 476. Number Complement 自制答案
- Leetcode 48. Rotate Image 自制答案
- Leetcode 477. Total Hamming Distance 自制答案
- leetcode 461
- leetcode解题之461 # Hamming Distance Java版
- [LeetCode461]Hamming Distance
- python核心编程(第二版)参考答案(自制)--第六章·序列:字符串、列表和元组(Part2)
- leetcode 461:Hamming Distance
- Leetcode动态规划题答案
- leetcode--TWO SUM延伸(假设答案不唯一、假设输入有相同数字)
- LeetCode 第三题,官方给的标准答案的一个分析,利用空间换时间,将复杂度降到了O(n)
- LeetCode 461 617 500 476 575 637
- Leetcode 461 Hamming Distance
- leetcode(461) Hamming Distance 简单题
- C++ Solution of LeetCode 461 Hamming Distance
- python核心编程(第二版)参考答案(自制)--第五章·数字
- [leetcode]461-HanmmingDistance
- leetcode-461 Hamming Distance
- leetcode-461-Hamming Distance
- leetcode-461(Hamming Distance)