编写函数,判断一个4位数是否为回文数。
时间: 2024-05-09 10:21:44 浏览: 15
好的,以下是一个简单的Python代码实现,用来判断一个4位数是否为回文数:
```python
def is_palindrome(num):
num_str = str(num)
return num_str == num_str[::-1]
# 测试案例
print(is_palindrome(1234)) # False
print(is_palindrome(1221)) # True
```
解释一下, `is_palindrome()` 函数将整数 `num` 转换为字符串,然后用切片 `[::-1]` 反转字符串,最后与原字符串比较是否相等,若相等则说明是回文数,返回 True,否则返回 False。
希望可以帮到你!如果你还有其他问题,可以继续提问。
相关问题
判断输入的4位数整数是否为回文数
可以使用以下代码判断输入的4位数整数是否为回文数:
```
local function is_palindrome(num)
local str = tostring(num)
local len = string.len(str)
for i = 1, len / 2 do
if string.sub(str, i, i) ~= string.sub(str, len - i + 1, len - i + 1) then
return false
end
end
return true
end
local num = 1234 -- 输入的4位数整数
if is_palindrome(num) then
print("是回文数")
else
print("不是回文数")
end
```
注意:这里使用了 Lua 语言编写的函数,可以判断输入的整数是否为回文数。
c语言中编写判断回文数的有参函数,在main函数中输入一个五位数,调用函数判断是否为回文数,是的话返回1输出,不是的话返回0输出
以下是判断五位数回文数的C语言函数实现及main函数的代码:
```c
#include <stdio.h>
#include <string.h>
int isPalindrome(int num);
int main() {
int n;
printf("请输入一个五位数:");
scanf("%d", &n);
if (isPalindrome(n)) {
printf("%d 是回文数\n", n);
} else {
printf("%d 不是回文数\n", n);
}
return 0;
}
int isPalindrome(int num) {
char str[6];
sprintf(str, "%d", num);
int len = strlen(str);
if (len != 5) {
return 0;
}
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
return 0;
}
}
return 1;
}
```
函数isPalindrome接收一个整数参数num,将其转化为字符串,然后通过比对字符串的首尾字符是否相同来判断该数是否为回文数。如果是回文数,函数返回1,否则返回0。在main函数中,先输入一个五位数,然后调用isPalindrome函数来判断该数是否为回文数,并输出结果。请注意,在isPalindrome函数中,我们还加入了一个判断,如果输入的数字不是五位数,直接返回0。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)