Next Palindrome

So first question is what is palindrome number. Palindrome number is when you reverse that number you will get same number. Now what is our problem.

For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output.

So here is the example.

If the input is 12 then output is 22 as the next palindrome after 12 is 22.

Likewise If the input is 123 then output is 131 as the next palindrome after 123 is 131.

So according to you what should be the logic for this problem.

Take one number after our input, check if it is palindrome or not, then if it is palindrome then print it otherwise check next number and so on. So if we are thinking like this then we are thinking it in a wrong way. I will explain what is the actual logic for this that is better then this.

Letβs take example of 122.

So first you need to calculate the string length of the number. So in our example the length is 3. I will tell you later on why we have calculated the length.

Here if your number is 123456789, then at first step our left most digit is β1β and right most digit is β9β. At the second step our left most digit is β2β and right most digit is β8β. At the third step our left most digit is β3β and right most digit is β7β. At the fourth step our left most digit is β4β and right most digit is β6β. At the fifth step our left most and right most digit is only β5β.

So I think you have got me.

Now for the number 122 left most digit is β1β and right most digit is β2β. Now you need to check whether these 2 digits are same or not. If they are not same then we have to increment right digit β1β, so our number will become β123β. Now again you need to do that process whether left most and right most digits are same or not. Here they are not same, so that we have to increment right digit by β1β, so our number will become β124β. This process we will do till β131β. When we will reach to the number β131β our left most and right most number will become same. So we will move towards next left-right combination. For the next left-right combination our left number is 3 and right is also 3. So we will stop there and 131 will become our next palindrome.

Here is the link for the problem.

Here is the link of the program in CPP with line by line explanation.

As this is my first post, please give as much as heart possible if you liked it.

Thank you.

1 Like