Members,
What I am trying to do is to right or left shift the digits of an Int32
(not the bits!!).
So if shift the constant:
123456789
by 3
I should get
789123456
So no digits get lost, because we talk about a circular shift. After a bit of testing I've come up with this method, which works:
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;
}
}
The way I am looking for should be an arithmetic solution, not a string conversion and then the rotation. I also assume that:
- The Int32 value has no 0-digits in it, to prevent any loss of digits.
- The Int32 is a non-negative number
- A positive Rotation integer should shift to the right, and negative one to the left.
My algorithm already does all of that, and I like to know if there are way to tweak it a bit, if there is a better arithmetic solution to the problem?