之前询问过,但由于缺乏细节而被关闭。所以这里有更多信息
我正在 cp 上工作,没有移位或旋转。
支持
我可以看到如何使用重复添加到自身来向左移动。我可以通过在移位前测试最左边的位并在移位后将其或到最右边来进行旋转。
但我想不出右移机制
这是使用
+
、-
和 &
的 C++ 示例:
#include <numeric>
template<class T>
T rightshift(T value, int steps) {
T div = 1;
while(steps--) div += div; // steps=1 => 2, 2 => 4 etc.
// zero out the bits that will be shifted out so that
// value will be evenly divisible by div:
T mask = std::numeric_limits<T>::max() - (div - 1);
value &= mask;
T res = 0;
while(value) { // subtract div until value reaches zero
value -= div;
++res; // and count the number of times we subtract
}
return res;
}