Leetcode 461 Hamming Distance 自制答案
来源:互联网 发布:怎么删除管家婆数据 编辑:程序博客网 时间:2024/06/05 14:19
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.答案描述上来说,就是找出两个数的异或位的个数。
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; }}
0 0
- Leetcode 461 Hamming Distance 自制答案
- Leetcode 477. Total Hamming Distance 自制答案
- [LeetCode-461]Hamming Distance
- Leetcode 461 Hamming Distance
- Leetcode 461 Hamming Distance
- leetcode-461-Hamming Distance
- leetcode 461: Hamming Distance
- leetcode--461 : Hamming Distance
- 【LeetCode】461Hamming Distance
- LeetCode #461: Hamming Distance
- LeetCode 461 Hamming Distance
- Leetcode #461 Hamming Distance
- 【LeetCode】461 Hamming Distance
- LeetCode 461 Hamming Distance
- leetcode.461 Hamming Distance
- LeetCode-461 Hamming Distance
- leetcode-461(Hamming Distance)
- 【LeetCode】461 Hamming Distance
- 工厂方法模式
- 混合背包
- deep-learning基本概念链接总结
- 03-树2 List Leaves (25分)
- 大小写转换问题
- Leetcode 461 Hamming Distance 自制答案
- LightOJ
- LintCode 二叉树的后序遍历
- 搬砖中的小事之代码(五)--maven项目的各种异常以及解决办法
- CSDN日报20170421 ——《程序员必知的七个图形工具》
- 多数据库服务器应用实现主从同步从而读写分离
- Wolf从零学编程-用Django撸个Blog(八)服务器部署
- 潜水员
- JavaScript作用域和var的关系