您的位置:首页 > 编程语言

编程珠玑(1):将一个n元一维向量向左旋转i个位置。例如当n=8且i=3时,向量abcdefgh 旋转为defghabc

2014-04-29 17:33 525 查看
问题:

        将一个n元一维向量向左旋转i个位置。例如当n=8且i=3时,向量abcdefgh旋转为defghabc。

在有限的资源内解决问题的方法:

    实际上是一种循环左移。我写的代码如下:

#include<stdio.h>
#include<malloc.h>

int main(void)
{
int i, n, k = 0, j;
int m = 0;
int num = 0; //每一个字符都会移动记录移动的个数

char *p;

char temp;

printf("please input the number n and i\n");
scanf("%d%d", &n, &i); //字符串的字符数以及循环左移个数

p =(char*)malloc(sizeof(char)*(n+1));
printf("please input the string\n");
scanf("%s", p); //输入字符

temp = p[0];
while(num != n ) {
j = 1;
while((k + i * j) % n != m) {
p[(k+i*(j-1))%n] = p[(k+i*j)%n];
j++;
num++;
}
m++;
p[(k+i*(j-1))%n] = temp;
k++;
num++;
temp = p[k];

}

printf("%s", p);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: