简体   繁体   English

在两个整数之间交换最右边的N位

[英]Swap right-most N bits between two integers

This question was asked during an onsite C++ coding interview. 在现场C ++编码访谈期间询问了这个问题。 I did NOT provide a good answer during that interview. 在那次采访中我没有提供一个好的答案。 So I was hoping to get feedback and suggestions from folks here at stack overflow. 所以我希望在堆栈溢出时得到人们的反馈和建议。 Now that I've had some more time to come up with a solution, I believe that I wrote a decent solution. 现在我已经有更多的时间来提出解决方案了,我相信我写了一个不错的解决方案。 I think this works OK as along as a and b refer to different integers. 我认为这样可行,因为ab指的是不同的整数。 If a and b refer to the same integer, then that integer would be be clobbered to 0. 如果ab引用相同的整数,那么该整数将被破坏为0。

void SwapRightMostNBits(int& a, int& b, unsigned int n){

    if (n>31) { n=31; }
    int mask=static_cast<int>(pow(2,n)-1);

    a ^= (b & mask);
    b ^= (a & mask);
    a ^= (b & mask);
}

I think the intended trick here is 我认为这里的目的是

void SwapRightMostNBits(unsigned int& a, unsigned int& b, unsigned int n){

    unsigned int mask=(1U<<n) -1;
    unsigned int diff = (a^b) & mask;

    a ^= diff;
    b ^= diff;
}

Note that this uses 3 XOR's, like your solution, but only one masking operation. 请注意,这与您的解决方案一样使用3个XOR,但只使用一个屏蔽操作。 Plus, this is way friendlier on the CPU registers. 另外,这在CPU寄存器上更友好。 There are no false dependency chains. 没有虚假的依赖链。 And finally, it works if &a==&b . 最后,如果&a==&b ,它可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当选择最左边或最右边的元素作为枢轴时,快速排序显然采用O(n ^ 2) - Quick sort apparently taking O(n^2) when left or right-most element is selected as pivot 查找列表的最左边和最右边的点。 std :: find_if正确的方法吗? - Finding the left-most and right-most points of a list. std::find_if the right way to go? 如何在两个文件之间交换整数? - How do you swap integers between two files? C++ 你如何在 N 个整数中找到一个具有最相似位的数字? - C++ how would you find a number with the most similar bits in N integers? 最小的n位整数c,具有k 1位,是两个n位整数的总和,其中g,h位设置为1(动态编程) - Smallest n-bit integer c that has k 1-bits and is the sum of two n-bit integers that have g, h bits set to 1(dynamic programming) 除以“ 6”作为最右边数字的整数输入之外的任何整数输入均可,但是诸如…6之类的任何数字都会导致分段错误,为什么? - Any integer input except one with “6” as the right-most digit works, but any number like …6 leads to segmentation fault, why? 交换两个类实例的最安全方法 - the most safe way to swap two class instance 在 C++ 中交换 unsigned int 中两个最低位的最快方法 - The fastest way to swap the two lowest bits in an unsigned int in c++ 检查是否设置了1到n之间的k中的所有位 - Checking if all bits in k between 1 to n are set 用于计算位或找到最右边|最左边的位的高效按位运算 - Efficient bitwise operations for counting bits or find the right|left most ones
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM