如何找到最近的回文数?

时间:2016-02-26 19:47:39

标签: java algorithm palindrome

我试着在java中编写一个程序来找到回文,有人让我在其中添加一个扭曲,并且扭曲就像这样我们必须找到该数字是否是回文,如果没有那么我们必须找到最近的回文数。例如,如果输入的数字是37,则有两个数字可以是附近的回文,一个是33而另一个是44,但是更近的是33,所以这里33是答案。我努力写了但没有成功:(

import java.io.*;  
public class NearestPalindrome {  
static int i,j,n,m,f,r=0,g,p1,p2,c1=0,c2=0,a;  
static boolean k;  
public static void main (String []agrs)throws IOException  
{
   BufferedReader A = new BufferedReader(new InputStreamReader(System.in));  
   System.out.println("This Program Is Created For Checking Whether The Number Entered Is Palindrome, If Not Find The Nearest Palindrome..");  
   System.out.println("Please Enter Number:-");  
   n=Integer.parseInt(A.readLine());
   f=n;  
   NearestPalindrome.Palindrome(f);  
   if(r==f)
   {System.out.println("This Is A Palindrome Number:-"+r);}
   else
   {
       for(i=n;((c1==1)&&(c2==1));i--)
       {
           NearestPalindrome.Palindrome(i);  
           NearestPalindrome.Palindrome(j);  
           if(k=true)  
           { if(r==i)  
           {   p1=i;  
           c1++;  
           }  
           if(r==j)  
               {p2=j;  
               c2++;  
               }  
               }  
           }  
       if((n-p1)>(p2-n))    
       {
        System.out.println("The Nearest Palindrome Is:-"+p2);  
       }  
       else  
        System.out.println("The Nearest Palindrome Is:-"+p1);  

       }  

   }  
public static boolean Palindrome (int x)
{


    for(i=0;x>0;i++)
       {
           m=x%10;
           r=r*10+m;
           x=x/10;   
       }  
    if(n==r)
    {k=true;}
    else
        k=false;
return k;
}  

}

8 个答案:

答案 0 :(得分:3)

可以更有效地完成。

假设我们有N个数字。让我们找到长度N / 2的前缀。之后,您可以使用2个最近的前缀构建3个可能的答案,并找到最近的回文(您应该在这里考虑角点情况)。

示例:

号码123456789的{​​{1}}前缀长度为1234。最近的前缀:9/2 = 41233

然后我们只构建3个候选人:1235123353321123454321

123555321

所以最近的回文将是abs(123456789 - 123353321) = 103468 abs(123456789 - 123454321) = 2468 abs(123456789 - 123555321) = 98532

UPD:在这种情况下你也必须尝试所有可能的中间数字。

答案 1 :(得分:0)

这应该让你朝着正确的方向前进

public class MyClass {

    public int findNearestPalindrome(int numberEntered) {
        int lowerPalidrome = getLowerPalindrome(numberEntered);
        int higherPalindrome = getHigherPalindrome(numberEntered);
        if (Math.abs(numberEntered - lowerPalindrome) < Math.abs(numberEntered - higherPalindrome) {
            return lowerPalindrome;
        } else {
            return higherPalindrom;
        }
    }

    public int getLowerPalindrome(int baseNumber) {
        for (int i = baseNumber; i > 0; i--) {
            //do logic to find palindrome and return it
        }
    }

    public int getHigherPalindrome(int baseNumber) {
        for (int i = baseNumber; i < LARGE_NUMBER; i++) {
            //do logic to find palindrome and return it
        }
    }
}

请记住,肯定有多种方法可以做到这一点。例如,您可以使用while循环,而不是for循环。我希望这有帮助!

编辑:如果你真的想压缩代码我建议你创建一个找到回文并在两种方法中使用它的方法。

答案 2 :(得分:0)

    import java.util.*;
    import java.lang.*;
    import java.io.*;
    class GFG
     {  public static int findcount(int n)
     {
         int count=0;
         while(n!=0)
         {
             n=n/10;
             count++;
         }
         return count;
     }
public static int findpalindrome(int arr)
 {
     int rem=0,count=0;
    while(arr>0)
    {
        rem=arr%10;
        count=(count*10)+rem;
        arr=arr/10;
    }
     return count;
 }
public static void main (String[] args) 
 {
 //code
 Scanner sc=new Scanner(System.in);
 int test=sc.nextInt();

 while(test-->0)
 { 
    int n=sc.nextInt();
     int res=0,flag=0,flag11=0,j=n+1,i=n-1;
     int aa=0,bb=0;
     if(findcount(n)==1 || (n==findpalindrome(n)) )
        System.out.println(n);
     else
     { 

         for(i=n-1;i>0;i--)
         {

          if(i==findpalindrome(i))
          {    
              aa=i;
              break;
          }  

         }
         while(flag!=1)
         { 
          if(j==findpalindrome(j))
          {    
              bb=j;
              flag=1;
              break;
          }
         j++;  
         } 
       int dif1=Math.abs(n-aa);
       int dif2=Math.abs(n-bb);
       if((dif1==dif2) || (dif1<dif2))
        System.out.println(aa);
       else
       System.out.println(bb);
     }

 }
 }

}

答案 3 :(得分:0)

使用具有数组和StringBuilder的基本Java的代码

    package newPackage;

public class AmazonQn6FindNearestPalindromeNumber {
    static int before;
    static int after;
    public static void main(String[] args) {
        System.out.println();

        int num=1221;
        AmazonQn6FindNearestPalindromeNumber n1=new AmazonQn6FindNearestPalindromeNumber();

        before = num-1;
        after = num+1;


        int[] checkPalindrome= new int[2];

        do {
            checkPalindrome = n1.checkPalindrome(before, after);        
            if((checkPalindrome[0] >0)||(checkPalindrome[1] >0)) {
            System.out.println("Numbers are");
            for(int n:checkPalindrome) {
                System.out.println(n);
            }


            if(checkPalindrome[0]!=0)
                System.out.println("Nearest Palindrome is "+checkPalindrome[0]);

            if(checkPalindrome[1]!=0)
                System.out.println("Nearest Palindrome is "+checkPalindrome[1]);

            break;
            }
        //  checkPalindrome = n1.checkPalindrome(before, after);

        }while((checkPalindrome[0] ==0)||(checkPalindrome[1] ==0));

    }

    public int[] checkPalindrome(Integer n, Integer m) {
        before = before-1;
        after = after+1;
        int[] array = new int[2];

        String stringn = n.toString();
        StringBuilder string1 = new StringBuilder(stringn);
        System.out.println(string1);
        StringBuilder string2 = string1.reverse();
        System.out.println(string2);
        if(stringn.equals(string2.toString()))
        {   
            array[0]=n;
            System.out.println("Element in n" +array[0]);

        }

        String stringm = m.toString();
        StringBuilder string3 = new StringBuilder(stringm);
        System.out.println(string3);
        StringBuilder string4 = string3.reverse();
        System.out.println(string4);

        if(stringm.equals(string4.toString()))
        {
            array[1]=m;
            System.out.println("Element in m" +array[1]);

        }

        return array;

    }

}

答案 4 :(得分:0)

找到最近回文的最简单代码。 例如,如果输入为37。到37的最近回文数为33和44。但是差分别为4和7。因此输出为33。如果两种情况下的差均相等,则将打印两个数字。

package demo;

import java.util.Scanner;

import javax.swing.text.html.FormSubmitEvent;

public class Increment {


    public static boolean Plaindrome(int n) {
          int r,sum=0,temp;

          temp=n;    
          while(n>0){    
           r=n%10;  
           sum=(sum*10)+r;    
           n=n/10;    
          }    
          if(temp==sum)    
              return true;
          else    
           return false; 

        }  
    public static int  greaterpalindrome(int k) {
        while(!Plaindrome(k)) {

             k++;

         }
        return k;
    }
    public static int  smallerpalindrome(int s) {
        while(!Plaindrome(s)) {

            s--;

         }
        return s;}

    public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);
         int value = scan.nextInt();

         int greater = greaterpalindrome(value+1);

         int smaller = smallerpalindrome(value-1);

         if (Math.abs(value-greater)==(value-smaller)) {
                System.out.println(greater+" "+smaller);
            }
            else if (Math.abs(value-greater)>(value-smaller)) {
                System.out.println(smaller);
            }
            else {
                System.out.println(greater);
            }

        } } 

答案 5 :(得分:0)

试试下面的代码片段:

public class Sample{
    public static void main(String[] args) throws InterruptedException {
        Scanner scan = new Scanner(System.in);
        
        System.out.print("Enter val: ");
        
        int entry = scan.nextInt();
        int entryN = entry;
        int entryP = entry;

        while(true) {
            if (isPolindrom(entry)) {
                System.out.println(entry);
                break;
            } else if (isPolindrom(--entryN)) {
                System.out.println(entryN);
                break;
            } else if (isPolindrom(++entryP)){
                System.out.println(entryP);
                break;
            }
        }   
        
        System.out.println("Best hakiki mürşit is a science :)");
        
    }

    private static boolean isPolindrom(int a) {
        int val1 = a;
        int last = 0;
        int size = String.valueOf(val1).length();
        
        for(int i = size; i > 0 ; i-- ) {
            
            last += (val1 % 10) * (int) Math.pow(10, (i-1));
            val1 = (val1 - (val1 % 10)) /10;
        }
        if (a == last) {
            return true;
        } else {
            return false;
        }       
        
    }
}

答案 6 :(得分:-1)

 declare @num integer
 set @num = 10

 if (@num < 10)
 begin
   print('hello')
   set @num = @num +1
 end
 else begin
   print('over')
   set @num = @num +1
 end

答案 7 :(得分:-2)

此代码是使用nearestPalindrome(int number)方法和其他方法使用nextPalindrome(int number)查找NEXT Palindrome数字来查找NEAREST Palindrome数字。

package com.amit.palindrome;

public class Palindrome {

    public static void main(String[] args) {
        Palindrome test= new Palindrome();
        int number=135625978;
        System.out.println("Given Number is :"+number);

        int nearestPolyNum=test.nearestPalindrome(number);
        int nextPolyNum=test.nextPalindrome(number);
        System.out.println("Nearest Palindrome Number is :"+nearestPolyNum);
        System.out.println("Next Palindrome Number is :"+nextPolyNum);
    }

    public int nextPalindrome(int number){
        int nextPoly=0;
        if(number>9){
            do {
                String revString = "";
                String numString=""+number;
                int numLength=numString.length();

                for(int i=numLength-1;i>=0;i--){
                    revString += numString.charAt(i);
                    if(numString.equals(revString)){
                        nextPoly=Integer.parseInt(revString);
                        return nextPoly;
                    }
                }
                number=number+1;
            } while(nextPoly!=number);
            return nextPoly;
        }
       return number;
    }



    public int nearestPalindrome(int number){

        if(number>9){
                String revString = "";
                String numString=""+number;
                int nearestPoly=0;
                int numLength=numString.length();           

                    String anotherHalfNumber=null;
                    int halfNum = numLength/2;
                    String firstHalfNumber=numString.substring(0, halfNum);
                    if(numLength%2==0){
                        anotherHalfNumber=numString.substring(halfNum);
                    }else{
                        anotherHalfNumber=numString.substring(halfNum+1);
                    }               
                    for(int i=firstHalfNumber.length()-1;i>=0;i--){
                        revString += firstHalfNumber.charAt(i);                

                    }
                    int intAnotherHalfNumber=Integer.parseInt(anotherHalfNumber);
                    int reverseFirstHalfNumber=Integer.parseInt(revString);
                    int adjustedNumber = intAnotherHalfNumber-reverseFirstHalfNumber;
                    nearestPoly = number-adjustedNumber;
                    return nearestPoly;
        }
         return number;
    }
}