LeetCode解题思路:461. Hamming Distance

本文介绍了如何计算两个整数之间的汉明距离,即二进制表示中不同位的数量。提供了两种C语言实现方法,一种是逐位检查,另一种是利用位移运算进行优化。

 

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 ≤ xy < 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.

题意:找到两个数的汉明距离,即两个数转换成二进制后有多少位不相同。
基本思路:
两数直接按位异或,如某一位两数相同则为0,反之为1。然后变成了数异或结果有多少个1。查1的方法有很多,这里不是重点留到后面再说,这里面先使用一种
最原始的。这道题没有复杂的内存分配,所以用c和c++写法是类似的,所以写了c。
 1 int hammingDistance(int x, int y) {
 2     int z = x ^ y;
 3     int cnt = 0;
 4     for( ; z > 0; )
 5     {
 6         if(z%2 == 1)//除2余数为1,就在统计结果上加1,这里是最通俗的想法,并不是最简洁写法
 7             cnt++;
 8         z /=2 ;//将z除2 ,统计下一位是否为1
 9     }
10     return cnt;
11 }

以上就是这道简单难度通过率最高的题的思路,运行时间3ms。

附上我写的最简写法。

1 int hammingDistance(int x, int y) {
2     int z = x ^ y,cnt=0;
3     for(int i=0;i<32;i++) cnt+=(z>>i)&1;
4     return cnt;
5 }

 



转载于:https://www.cnblogs.com/hellomotty/p/7302265.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值