
问题
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x 和 y,计算它们之间的汉明距离。
注意:0 ≤ x, y < 231.
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑上面的箭头指出了对应二进制位不同的位置。
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.
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.
示例
public class Program { public static void Main(string[] args) { var a = 16; var b = 13; var res = GetSum(a, b); Console.WriteLine(res); a = 168; b = 136; res = GetSum2(a, b); Console.WriteLine(res); Console.ReadKey(); } public static int GetSum(int a, int b) { //按位取异或 int result = a ^ b; //判断是否需要进位 int forward = (a & b) << 1; if(forward != 0) { //如有进位,则将二进制数左移一位,进行递归 return GetSum(result, forward); } return result; } public static int GetSum2(int a, int b) { while(b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } }
以上给出2种算法实现,以下是这个案例的输出结果:
True False
分析:
显而易见,IsPowerOfTwo 的时间复杂度为: ,IsPowerOfTwo2 的时间复杂度为:
。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/4064。