C语言实现

在C语言中,你可以通过分别提取出五位数的各个位(万位、千位、百位、十位、个位),然后比较这些位是否满足回文数的条件。

c复制代码
 #include <stdio.h>  
 
 #include <stdbool.h>  
 
   
 
 bool isPalindrome(int x) {  
 
     // 排除非五位数和负数  
 
     if (x < 10000 || x > 99999) {  
 
         return false;  
 
     }  
 
       
 
     // 提取各个位  
 
     int tenThousand = x / 10000; // 万位  
 
     int thousand = (x / 1000) % 10; // 千位  
 
     int hundred = (x / 100) % 10; // 百位  
 
     int ten = (x / 10) % 10; // 十位  
 
     int one = x % 10; // 个位  
 
       
 
     // 比较回文  
 
     return (tenThousand == one) && (thousand == ten);  
 
 }  
 
   
 
 int main() {  
 
     int number;  
 
     printf("请输入一个五位数: ");  
 
     scanf("%d", &number);  
 
       
 
     if (isPalindrome(number)) {  
 
         printf("%d 是回文数\n", number);  
 
     } else {  
 
         printf("%d 不是回文数\n", number);  
 
     }  
 
       
 
     return 0;  
 
 }

Python实现

Python 实现会相对简洁一些,因为 Python 提供了更丰富的字符串操作功能。但题目要求的是数字,所以我们可以先将数字转换为字符串,然后检查其是否为回文数。

方法1:字符串比较

python复制代码
 def is_palindrome(x):  
 
     # 排除非五位数和负数  
 
     if not 10000 <= x <= 99999:  
 
         return False  
 
       
 
     # 转换为字符串并检查回文  
 
     return str(x) == str(x)[::-1]  
 
   
 
 number = int(input("请输入一个五位数: "))  
 
 if is_palindrome(number):  
 
     print(f"{number} 是回文数")  
 
 else:  
 
     print(f"{number} 不是回文数")

方法2:数字提取比较(类似C语言)

虽然Python中不常用这种方法,但为了与C语言的方法保持一致,我们也可以这样做:

python复制代码
 def is_palindrome_number(x):  
 
     # 排除非五位数和负数  
 
     if not 10000 <= x <= 99999:  
 
         return False  
 
       
 
     # 提取各个位  
 
     ten_thousand = x // 10000  
 
     thousand = (x // 1000) % 10  
 
     hundred = (x // 100) % 10  
 
     ten = (x // 10) % 10  
 
     one = x % 10  
 
       
 
     # 比较回文  
 
     return ten_thousand == one and thousand == ten  
 
   
 
 number = int(input("请输入一个五位数: "))  
 
 if is_palindrome_number(number):  
 
     print(f"{number} 是回文数")  
 
 else:  
 
     print(f"{number} 不是回文数")

这两种Python方法都可以实现题目要求,但通常第一种方法(使用字符串操作)在Python中更为常见和简洁。

一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。_回文数