会员,
我要做的是右移或左移 an 的数字Int32
(而不是位!!)。
所以如果改变常数:
123456789
经过3
我应该得到
789123456
所以没有数字会丢失,因为我们谈论的是循环移位。经过一番测试,我想出了这个方法,它有效:
static uint[] Pow10 = new uint[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, uint.MaxValue };
static uint RotateShift10(uint value, int shift)
{
int r = (int)Math.Floor(Math.Log10(value) + 1);
while (r < shift)
shift = shift - r;
if (shift < 0) shift = 9 + shift;
uint x = value / Pow10[shift];
uint i = 0;
while (true)
{
if (x < Pow10[i])
return x + (value % Pow10[shift]) * Pow10[i];
i += 1;
}
}
我正在寻找的方式应该是算术解决方案,而不是字符串转换然后旋转。我还假设:
- Int32 值中没有 0 位数字,以防止任何数字丢失。
- Int32 是一个非负数
- 一个正的 Rotation 整数应该向右移动,负一个向左移动。
我的算法已经完成了所有这些,我想知道是否有办法对其进行一些调整,是否有更好的算术解决方案来解决这个问题?