📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Recursion is a powerful technique in programming where a function calls itself to solve a problem. In the context of palindromes, recursion can simplify the process of checking if a number is the same forward and backward.
Definition
A palindrome is a sequence of characters that reads the same forward and backward. A recursive approach to determine if a number is a palindrome involves comparing the first and last digits and, if they match, recursively checking the remaining middle part.
2. Program Steps
1. Define the number to be checked for palindromicity.
2. Create a recursive function to check if the number is a palindrome.
3. Call the recursive function and pass the number to it.
4. Print the result of the recursive check.
3. Code Program
# Step 1: Define the number number = 12321 # Recursive function to check for a palindrome def is_palindrome_recursive(n, original_number=None): # Initialize original_number during the first call if original_number is None: original_number = n # Step 2: Base case, if the number has one or no digit, it's a palindrome if n < 10: return n == (original_number % 10) # Remove the last digit and compare it with the first if n % 10 != original_number // (10 ** (len(str(n)) - 1)): return False # Remove the first and last digit and make a recursive call n = (n % (10 ** (len(str(n)) - 1))) // 10 return is_palindrome_recursive(n, original_number // 10) # Step 3: Call the recursive function is_palindrome = is_palindrome_recursive(number) # Step 4: Print the result print(f"The number {number} is a palindrome: {is_palindrome}")
Output:
The number 12321 is a palindrome: True
Explanation:
1. number is assigned the value 12321.
2. is_palindrome_recursive is defined to check if n is a palindrome. It takes n and an optional original_number parameter, which remains unchanged in recursive calls.
3. If n is less than 10, it means we're down to the last digit, and we compare it with the last digit of original_number.
4. If the current last digit of n doesn't match the current first digit of original_number, it returns False.
5. Otherwise, it strips the first and last digit from n and original_number, respectively, and recurses with the smaller numbers.
6. The final print statement shows the result of the recursive palindrome check.
Comments
Post a Comment
Leave Comment