LeetCode 461: Hamming Distance
2017-07-12 21:07
295 查看
LeetCode 461: Hamming Distance
根据上面的例子可知,我们需要判断两个数值二进制为有多少位不同,所以可以直接根据十进制向二进制的转换过程而获得结果。需要注意的是必须两个数都为0时才能判断停止。
Solution中的升级版
思路:先将两个数进行按位异或,然后判断异或获得的结果中有几个1。
题目大意
求两个整型数x,y的汉明距离。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. 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.
给定代码
int hammingDistance(int x, int y) { }
思路分析&相应代码
我的初级版根据上面的例子可知,我们需要判断两个数值二进制为有多少位不同,所以可以直接根据十进制向二进制的转换过程而获得结果。需要注意的是必须两个数都为0时才能判断停止。
int hammingDistance(int x, int y) { int count = 0; while(x!=0 || y!=0){ if(x%2 != y%2){ count++; } x/=2; y/=2; } return count; }
Solution中的升级版
思路:先将两个数进行按位异或,然后判断异或获得的结果中有几个1。
int hammingDistance(int x, int y) { int dist = 0, n = x ^ y; while (n) { ++dist; n &= n - 1; } return dist; }
分析总结
难得首次提交就AC,虽然自己调试的时候还是有错误。Solution中还有大神只用了一行代码,也是666。私以为,我的方法是最笨的,当然也是我这种菜鸟最容易想到的,上面那种方法对于我来说的问题在于,对于位运算不够熟悉,所有完全想不到还可以那样来按位异或甚至获得二进制中1的个数,当时学C++的时候学的比较粗略,之后也没怎么练习。相关文章推荐
- LeetCode@Bit_461_Hamming_Distance
- leetcode 461 Hamming Distance C++
- 刷题的日常[Leetcode]——461)Hamming Distance and 476)Number complement
- leetcode(461) Hamming Distance 简单题
- leetcode 461: Hamming Distance
- LeetCode461 Hamming Distance java The Hamming distance between two integers is the number osoluotion
- LeetCode.192(461/477) Number 1 Bits & Hamming Distance & Total Hamming Dist(经典位运算应用,求解二进制其中1的个数)
- Leetcode 477 Total Hamming Distance
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- LeetCode Hamming Distance
- leetcode-477-Total Hamming Distance
- LeetCode之Hamming Distance
- LeetCode Total Hamming Distance
- Hamming distance- leetcode
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- LeetCode Total Hamming Distance
- LeetCode Weekly Contest 13-TotalHamming Distance【中】
- Hamming Distance(leetcode)
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- leetcode 477 Total Hamming Distance C++