旋转整数以获得最大尾随二进制零
Rotate integer for maximum trailing binary zeros
给定 16 位数据,我需要(使用 C++11)找到最大化尾随零数的旋转。
例如(为清楚起见,使用 8 位),
10110001 -> 11011000 so rot=1
10000011 -> 11100000 so rot=2
etc.
显然,"蛮力"它很容易。但我怀疑有一个优雅的解决方案。
我认为代码中的一切都很清楚。类比左移。您可以在 cpp.sh 上进行测试
#include <iostream>
#include <string>
#include <bitset>
const int count_bits = 8;
int num_right_rotation(std::string number)
{
int max = 0;
int rotation = 0;
std::bitset<count_bits> one (number);
for(int i=0; i<count_bits; i++)
{
int max_temp = 0;
for(int j=0; j<count_bits; j++)
{
if(!one[j]) max_temp++;
else break;
}
if(max_temp > max)
{
max = max_temp;
rotation = i;
}
one = (one>>1) | (one<<count_bits-1);
}
return rotation;
}
int main()
{
std::cout << num_right_rotation ("10110001") << std::endl;
std::cout << num_right_rotation ("10000011") << std::endl;
return 0;
}
以下函数产生左旋转距离(因为您可能想在之后使用 std::rotate)。想法:走过位,当你偶然发现一个0时,从那里数零。使用模数绕在末端并继续计数:
#include <algorithm>
#include <iostream>
#include <string>
int rotation(std::string bits)
{
int max_pos = 0;
int max_count = 0;
for (int i = 0; i < bits.size();)
{
if (bits[i] == '0')
{
int count = 1;
for (; bits[(i + count) % bits.size()] == '0' && count < bits.size();
++count);
if (count > max_count)
{
max_pos = i;
max_count = count;
}
i += count;
}
else
{
++i;
}
}
return (max_pos + max_count) % bits.size();
}
int main()
{
std::cout << rotation ("10110001") << std::endl;
std::cout << rotation ("10000011") << std::endl;
return 0;
}
这是我正在考虑的"优雅解决方案"想法:假设我们正在测试 x = 1110 0000。
减去 1 得到 11011 1111。和 x ^ (x-1) = 0011 0000。
即,我们将始终得到这种形式的数字,具体取决于尾随零的数量。
尾随最多的零将产生最大的数字。
所以Python式伪代码可能看起来像:
iWinner = [x ^ (x-1) where x=rot(X,i) for i in range(16)].indexWithMaxValue()
在 C 语言中:
uint16_t x = 42;
uint16_t xWinner=0;
for(uint16_t i=0,yMax=0; i<16; i++) {
x = x << 1 + x >> 15; // rotate 1 left
uint16_t y = x ^ (x-1);
if( y > yMax ) {
yMax = y;
xWinner = x;
}
}
但是,我看不到任何利用C++来进一步清理它的方法。
相关文章:
- 从二进制文件中读取整数数组
- FlatBuffers/Protobuf 中是否有支持任意 24 位有符号整数定义的可移植二进制序列化架构?
- 读取二进制文件并解释为整数
- 将较大的整数写为二进制并读回它们会产生不好的结果
- C++ 将二进制字符串转换为整数或比较 2 个字符串以查找差异数
- 将二进制编码的无符号字符转换为整数
- 将整数的二进制数据转换为浮点数
- 将非数字字符串存储为二进制整数
- 如何在 gdb 中查看C++整数的二进制内容?
- 添加两个二进制数(整数数组)
- 将二进制转换为负整数
- 编译器C++如何在二进制代码中表示整数
- 除以 n 位二进制整数
- 如何在表达式计算器中处理二进制整数
- 将二进制整数转换为二进制分数
- 如何在 Haskell 中添加两个 n 位二进制整数
- 将二进制整数的向量转换为数字向量
- 读取二进制整数
- 无法从文件中读取简单的二进制整数?(C++)
- 在二进制整数 (C++) 中读取后,fstream 是否移动到下一个位置