461 Hamming distance
来源:互联网 发布:淘宝买家秀福利 合集 编辑:程序博客网 时间:2024/06/05 15:04
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.
这个题意大致就是 两个数a,b 把两个数转化为2进制数,然后找他们相同位数上的数字是不是不同,这些不同的个数加起来就是汉明距离.
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.
这个题意大致就是 两个数a,b 把两个数转化为2进制数,然后找他们相同位数上的数字是不是不同,这些不同的个数加起来就是汉明距离.
我的做法是这样:
做法1:
int hammingDistance(int x, int y) {int c = x^y, d = 0;//先用按位异或运算求出c,再计算c中1的个数while (c){if (c % 2 == 1){d++;}c /= 2;}return d;}
做法2:
int hammingDistance(int x, int y) {int res = 0, exc = x ^ y;while (exc) {++res;exc &= (exc - 1);//这个得用处就是把exc化为二进制后最右边的1变为0;看一共变了多少次,(就有多少个1)//还有个用,判断一个数(x)是否是2的n次方,if( (x&(x-1)) == 0 ) return 1;}return res;}
做法3:
int hammingDistance(int x, int y){if ((x ^ y) == 0) return 0;//看是不是相同的两个数return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);//运用递归,实际和第一种做法一个意思,//(x ^ y) % 2 就是一个计数器x,循环一次加次,可能加的是可能是1,hammingDistance(x / 2, y / 2)就是一直调用,直到(x ^ y) == 0,结束就依次跳出循环了,返回 return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);}
做法4:
class Solution {public:int hammingDistance(int x, int y) {int a[31], b[31];int c = 0;for (int i = 0; i<31; i++){if (x % 2 != 0){a[i] = 1;x = x / 2;}else{a[i] = 0;x = x / 2;}if (y % 2 != 0){b[i] = 1;y = y / 2;}else{b[i] = 0;y = y / 2;}if (a[i] != b[i])c++;}return c;}};
1 0
- [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
- 461 Hamming Distance
- LeetCode 461 Hamming Distance
- 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
- Linux 常用命令
- Android基础——适配安卓6.0新权限系统
- 2、swift开发iOS——swift语法
- 最纯粹的直播技术实战03-通过filter进行旋转及卡顿修复
- Android 实现底部弹出菜单
- 461 Hamming distance
- System.Web.Optimization 合并压缩技术的使用(转载)
- R语言入门-R语言环境安装与Rstudio安装
- Mockito 如何 mock 返回值为 void 的方法
- 自己实现链表数据结构 LinkedList
- Java 8 可重复注解的理解与应用
- NuGet的简单使用
- 【Codeforces E Hanoi Factory】+ 贪心 + 栈
- Jsp与javabean之间的关系