元素翻转

读编程珠玑,得知的两种元素串翻转方法,我简单实现了下

第一种是杂技翻转取模替换

 1 int gcd(int i, int j)
2 {
3 while (i != j)
4 if (i > j)
5 i -= j;
6 else
7 j -= i;
8 return i;
9 }
10
11 int main()
12 {
13 freopen("datain.txt", "r", stdin);
14 int i, rotdist, n;
15 char x[] = {"12345678"};
16 scanf("%d %d", &rotdist, &n);
17 for (i = 0; i < gcd(rotdist, n); i++)
18 {
19 int k, t = x[i], j = i;
20 while(1)
21 {
22 k = j + rotdist;
23 if (k >= n)
24 k -= n;
25 if (k == i)
26 break;
27 x[j] = x[k];
28 j = k;
29 }
30 x[j] = t;
31 }
32 printf("%s", x);
33 getch();
34 return 0;
35 }


第二种是求逆翻转相比之前方法要好

#include <stdio.h>

char a[] = {"123456789"};
void reverse(int pos, int n)
{
int i;
for (i = pos; i < (n+pos+1)/2; i++)
{
char t = a[i];
a[i] = a[n+pos+1 - i - 1];
a[n+pos+1 - i - 1] = t;
}
return ;
}

int main()
{
int rotdist =3, n = 9;
reverse(0, 2);
reverse(3, 8);
reverse(0, 8);
printf("%s", a);
getch();
return 0;
}



你可能感兴趣的:(元素)