#include <stdio.h>
#include <string.h>
int main() {
int k;
char str[1005];
// k
if (scanf("%d", &k) != 1) return 0;
// fgets
getchar();
//
if (fgets(str, sizeof(str), stdin) == NULL) return 0;
// fgets '\n'
int len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
len--;
}
//
if (len == 0) return 0;
// k k
k = k % len;
// k 0
if (k == 0) {
printf("%s\n", str);
return 0;
}
// 1. k
// len - k
printf("%s", &str[len - k]);
// 2.
// len - k
for (int i = 0; i < len - k; i++) {
putchar(str[i]);
}
printf("\n");
return 0;
}
This code reads an integer k and a string, then rotates the string to the right by k positions. It removes the newline from the input, adjusts k to be within the string length, and prints the last k characters followed by the first len-k characters.
- The rotation logic uses `k = k % len` to handle cases where k is larger than the string length, but check if this works correctly when k is negative or zero.
- The code prints the last k characters using `printf("%s", &str[len - k])`, but this assumes len - k is a valid starting index. Consider what happens if k is 0 or if len - k equals len.