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.