given a string str
which has length length
and a rotation amount n
rotate left is equivalent to
reverse(str, 0, n);
reverse(str, n, length);
reverse(str, 0, length);
rotate right is equivalent to
reverse(str, 0, length - n);
reverse(str, length - n, length);
reverse(str, 0, length);
Now you just need a reverse function.
Update:
I thought of how you can use mod's to make you always rotate in the right direction depending on the sign of n
.
e.g.
int mod = n % length;
if (mod != 0) { //if 0, don't rotate
reverse(str, 0, mod);
reverse(str, mod, length);
reverse(str, 0, length);
}
going through the various cases
if n == 5 and length = 10, mod = 5
if n == 16 and length = 10, mod = 6 -- rotating left by 16 = rotating left by 6
if n == 0 and length = anything, mod = 0
if n == -1 and length = 10, mod = 9 -- rotating right by 1 is the same as rotating left by 9
if n == -15 and length = 9, mod = 3 -- rotating right by 15 is the same as rotating left by 3