297. Python Program to Find the Next Palindrome Number
MediumPhase 2 · Practice
This one takes a few steps, but you know every tool it uses: while loops, break, and % and // to reverse a number.
Overview
A palindrome number reads the same from left to right and from right to left, like 7, 44 or 121. Finding the next one is a good practice question: you test numbers one by one until one fits.
Problem Statement
Freya watches the distance counter in the family car. It shows a whole number, and the number goes up by 1 at a time. Freya likes it when the counter shows a palindrome number. Read the number n that the counter shows now, and find the smallest palindrome number that is bigger than n.
- The answer must be bigger than
n. Ifnis a palindrome itself, it does not count. - Every number with one digit is a palindrome.
- To check a number, reverse its digits with
%and//. If the reverse equals the number, it is a palindrome.
Print one line: The next palindrome after 123 is 131, with your numbers in place of 123 and 131.
Examples
Example 1. Input 123 gives:
The next palindrome after 123 is 131
Why: the numbers 124 to 130 do not read the same both ways. 131 does, so it is the answer.
Example 2. Input 99 gives:
The next palindrome after 99 is 101
Why: 99 is a palindrome, but the answer must be bigger. 100 read backwards is 001, which is not 100. 101 is the same both ways.
Input
One whole number n, from 0 to 1000000. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line, as shown above. The tests try 8 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.
This is the last question of Phase 2 · Practice. The next question starts Phase 3.