面试问题:将一个整数转换为另一个整数所需的位交换次数
我的一个朋友在接受采访时被问到这个问题。我无法找到解决方案。 问题 -
编写一个函数来计算将一个整数转换为另一个整数所需的位交换次数。
A friend of mine was asked this question in an interview. I wasn't able to figure out a solution to this.
Question -
Write a function to calculate the number of bit swaps required to convert one integer to other.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
可用于找出哪些位不同的位运算是异或。异或值中的每个
1
将告诉两个整数之间的不同位。The bit operation which can be used to figure out which bits are different is xor. Each
1
in the xor value will tell the different bit between the two integers.面试问题不仅与解决方案有关,而且(这通常比寻找解决方案更重要)让您有机会展示如何解决此类新问题。你会如何开始呢?您还想了解更多信息来帮助您解决问题吗?您想使用任何标准函数(在任何常用的编程语言中)吗?
给我们你最好的机会,我们将扮演面试官并在你进行过程中进行提示......
Interview questions aren't only about solutions, they're also (and this is generally even more important that finding a solution) giving you the opportunity to show how you would tackle a novel problem such as this. How would you start on this ? Is there any further information you'd like to know to help you solve it ? Are there any standard functions (in any commonly-used programming language) you'd like to use ?
Give us your best shot, we'll play the interviewer(s) and prompt as you go ...
对值进行异或,然后计算结果中的个数
XOR the values and then count the number of ones in the result
我看不出这个问题有什么特别之处。迭代两个整数的位,通过 XOR 组合当前位并在结果不等于零时递增计数器,将给出两个值中不同的位数。
I fail to see anything special about this question. Iterating over the bits of both integers, combining the current bits via XOR and incrementing a counter if the result is not equal to zero will give you the number of bits that differ in both values.
不同的方法
查找二进制字符串并通过动态规划计算 Levenshtein 距离
Different approach
find and the binary string and calculate Levenshtein distance by dynamic programming
对 2 个数字(例如 a 和 b)进行异或,并计算 a^b 中的个数
我们可以做得更好一点,而不是简单地在检查最低有效位时重复移动 c,我们可以连续翻转最右边的位设置为 1,并计算 c 达到 0 所需的时间。操作 c = c & (c-1) 将清除 c 中设置为 1 的最右边位。
Take the XOR of 2 numbers (say a & b), and count the number of ones in the a^b
We can make it a bit better, rather than simply shifting c repeatedly while checking the least significant bit, we can continuously flip the rightmost bit set to 1 and count how long it takes c to reach 0. The operation c = c & (c-1) will clear the rightmost bit set to 1 in c.