A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.

Approach

We follow the computations from the string perspective on the given number, let's discuss a few cases,

Even Length Digit

Case 1: When the reversed left half is greater than the right half, we copy the first half to the second half.

Case 2: When the reversed left half is less than the right half, we increment the left half with one (with carry if required)

2. Odd Length Digit

Case 1: When the reversed left half is greater than the right half excluding the middle element, we copy the first half to the second half.

Case 2: When the reversed left half is less than the right half excluding the middle digit inclusive of carry operation to left, we increment the left half with one including the middle element

3. All 9s

We repeat the zeros with one length less than the number of 9s and appending with one on each side.

Code

In the below approach, we can use the BigInteger present in the System.Numerics namespace. It wasn't acceptable in the InterviewBit so I have coded the ParseAndIncrement method.

Reference

You've successfully subscribed to Coding Today

Great! Next, complete checkout for full access to Coding Today

Welcome back! You've successfully signed in.

Unable to sign you in. Please try again.

Success! Your account is fully activated, you now have access to all content.