方法一:
#include<stdio.h>
#include<string.h>
void left_rotate(char arr[], int k)
{
int i,j, len = strlen(arr);
k %= len;
for (i = 0; i < k; i++)
{
char tmp = arr[0];
for (j = 0; j < len - 1; j++)
{
arr[j] = arr[j + 1];
}
arr[len - 1] = tmp;
}
}
int main()
{
char arr[] = "abcdef";
int k;
scanf("%d", &k);
left_rotate(arr, k);
printf("%s", arr);
return 0;
}
方法二:
#include<stdio.h>
#include<string.h>
#include<assert.h>
void reverse(char* left, char* right)
{
assert(left && right);
while (left < right)
{
char tmp=*left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
void left_rotate(char arr[], int k)
{
int len = strlen(arr);
k %= len;
reverse(arr, arr + k - 1);
reverse(arr + k, arr + len - 1);
reverse(arr, arr + len - 1);
}
int main()
{
char arr[] = "abcdef";
int k;
scanf("%d", &k);
left_rotate(arr, k);
printf("%s", arr);
return 0;
}