📅  最后修改于: 2023-12-03 15:27:41.519000             🧑  作者: Mango
本文介绍了如何使用 C 编程语言来实现翻转句子和数字的算法。
翻转句子的算法可以通过以下步骤实现:
下面是实现翻转句子的示例代码:
#include <stdio.h>
#include <string.h>
void reverse(char *begin, char *end) {
char tmp;
while (begin < end) {
tmp = *begin;
*begin++ = *end;
*end-- = tmp;
}
}
void reverseWords(char *s) {
char *word_begin = NULL;
char *word_end = NULL;
char *temp = s;
while (*temp) {
/* skip spaces */
while (*temp && (*temp == ' '))
temp++;
/* mark the beginning of a word */
if (word_begin == NULL)
word_begin = temp;
/* find the end of the word */
if (*temp && (*temp != ' '))
word_end = temp;
temp++;
}
/* reverse each word in the sentence */
reverse(word_begin, word_end);
/* reverse the entire sentence */
reverse(s, temp-1);
}
int main() {
char s[] = "Hello World!";
printf("Before reverse: %s\n", s);
reverseWords(s);
printf("After reverse: %s\n", s);
return 0;
}
运行结果:
Before reverse: Hello World!
After reverse: World! Hello
翻转数字的算法可以通过以下步骤实现:
下面是实现翻转数字的示例代码:
#include <stdio.h>
int reverseNumber(int num) {
int rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
int main() {
int num = 12345;
printf("Before reverse: %d\n", num);
num = reverseNumber(num);
printf("After reverse: %d\n", num);
return 0;
}
运行结果:
Before reverse: 12345
After reverse: 54321
总结:
本文介绍了如何使用 C 编程语言来实现翻转句子和数字的算法。翻转句子的算法需要先将句子中的每个单词都翻转,再将整个句子进行翻转;翻转数字的算法需要逐位分离数字,然后将各位数字按照从右至左的顺序重新组合成一个数字。