Next nearest palindrome



Problem to find the next nearest palindrome in given value.



If the given string is equal to the reverse of the string means that is called Palindrome. Palindrome full Explain




Example-1:


Input    : n = 15 
Output   : 11


Example-2:


Input    : n = 35 
Output   : 33


Example-3:


Input    : n = 121
Output   : 131 111    









Solution




public class Main
{
    public static void main(String[] args) 
    {
        Main obj = new Main();

        int num = 121;

        int left = num-1;

        int right = num + 1;

        boolean f = true;

        while(f)
        {
            if(obj.checkpoli(String.valueOf(left)))
            {
                System.out.print(left+" ");

                f = false;
            }

            if(obj.checkpoli(String.valueOf(right)))
            {
                System.out.print(right);

                f = false;
            }

            left--;

            right++;
        }
    }

    private boolean checkpoli(String s)
    {
        int j = s.length()-1;

        for (int i=0;i<s.length();i++) 
        {
            if(s.charAt(i) != s.charAt(j))
            {
                return false;
            }

            j--;
        }

        return true;
    }
}
n = "121"

n = int(n)

m = n

n = n+1

k = 1

m = m-1

x = 1

while(str(n)!=(str(n)[::-1])):

    n+=1

    k+=1

x=1

while(str(m)!=(str(m)[::-1])):

    m -= 1

    x += 1

if(k==x):

    print(n,m)

elif(k<x):

    print(n)

else:

    print(m)



Output



131 111