Given an integer with an arbitrary number of numerical digits, write a function to check recursively if the integer is a palindrome, e.g., 5679765, (10%) and another function to check iteratively if the integer is a palindrome (10%). A palindrome here is a number that is the same forwards and backwards. Test both functions by giving any user input integer using the main function (5%).
时间: 2024-02-02 07:02:57 浏览: 76
Sure, I can help you with that! Here are the recursive and iterative functions to check if an integer is a palindrome:
Recursive function:
```python
def is_palindrome_rec(num):
str_num = str(num)
if len(str_num) <= 1:
return True
elif str_num[0] != str_num[-1]:
return False
else:
return is_palindrome_rec(str_num[1:-1])
```
Iterative function:
```python
def is_palindrome_iter(num):
str_num = str(num)
for i in range(len(str_num)//2):
if str_num[i] != str_num[-1-i]:
return False
return True
```
And here's a simple main function to test both functions:
```python
def main():
num = input("Enter an integer: ")
if is_palindrome_rec(num):
print(num, "is a palindrome (recursive)")
else:
print(num, "is not a palindrome (recursive)")
if is_palindrome_iter(num):
print(num, "is a palindrome (iterative)")
else:
print(num, "is not a palindrome (iterative)")
if __name__ == "__main__":
main()
```
Hope this helps!
阅读全文