用递归的方法输出有序回文数
时间: 2024-02-21 15:57:00 浏览: 27
有序回文数是指从小到大排列的回文数,例如:1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, ...。
以下是使用递归的方法输出有序回文数的代码:
```c
#include <stdio.h>
void printPalindrome(int n) {
if (n <= 0) {
return;
}
printf("%d ", n);
printPalindrome(n-1);
if (n < 10) {
printf("%d ", n);
}
}
int main() {
printPalindrome(9);
return 0;
}
```
该程序中的 `printPalindrome` 函数采用递归的方式输出有序回文数。当 `n` 的值小于等于 0 时,递归结束;否则,先输出 `n`,再递归输出 `n-1`,最后如果 `n` 小于 10,则再输出一次 `n`,以保证有序回文数的正确性。
程序的输出结果为:
```
9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9
```
相关问题
java用递归求回文数
下面是Java代码实现递归求回文数的方法:
```java
public static boolean isPalindrome(String str) {
if (str.length() <= 1) {
return true;
}
if (str.charAt(0) != str.charAt(str.length() - 1)) {
return false;
}
return isPalindrome(str.substring(1, str.length() - 1));
}
```
这个递归函数会不断地比较字符串的首尾字符是否相同,如果不相同就返回false,如果长度为1或0就返回true,否则就递归调用函数,将首尾字符去掉后的子串作为参数传入。
c语言递归求回文数
可以使用递归来判断一个数是否为回文数,代码如下:
```c
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[], int start, int end) {
// 递归结束条件
if (start >= end) {
return 1;
}
// 如果首尾字符不相等,返回0
if (str[start] != str[end]) {
return 0;
}
// 递归判断中间的字符是否为回文数
return isPalindrome(str, start+1, end-1);
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
if (isPalindrome(str, 0, len-1)) {
printf("%s 是回文数\n", str);
} else {
printf("%s 不是回文数\n", str);
}
return 0;
}
```
该程序将输入的字符串作为参数传递给 `isPalindrome` 函数,`start` 和 `end` 分别表示字符串的首尾字符的下标,通过递归的方式不断缩小范围,判断字符串是否为回文数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)