这是一个循环右移算法,需要两个临时空间,时间复杂度为O(n)。如有代码风格等不足之处望大家指出。
#include<stdio.h>
#include<string.h>
void CycleMovelight(char* s,int len,int n)
{
int temp1,temp2; //temp1存储的是下一个要交换的位置,temp2下一个要交换字符的临时存放区,s[0]作为临时交换
n=n%strlen;
for(int i=0;i<len-1;i++)//只需要n-1次就好
{
if(i==0) //对算法进行初始化
{temp1=n*(i+1)%len;temp2=s[temp1];s[temp1]=s[0];/*printf("%s\n",s);用来做测试*/}
if(i>0) //
{
temp1=n*(i+1)%len;
s[0]=s[temp1];
s[temp1]=temp2;
temp2=s[0];
/*printf("%s\n",s);用来做测试*/
}
}
}
int main()
{
char s[10];
int len,n;
scanf("%s",s);
scanf("%d",&n);
len=strlen(s);
CycleMovelight(s,len,n);
//printf("%s\n",s);
}
灵感来源:http://hi.baidu.com/shi51314/item/f91df6c834e02011515058d8