2016-05-12 41 views
0

問題是在給定數字後面找到最小的迴文數整數。用於查找下一個迴文的Java代碼 - 輸出錯誤

  1. 輸入整數即測試用例的數量。

  2. 在數組中輸入整數。

  3. 輸出:分別對應數組中每個整數的下一個迴文數整數。

有各種方法來解決這個問題(許多解決方案也是如此),但我不明白爲什麼我不能從這個代碼得到輸出。從多次運行代碼,我得出的結論是,如果任何測試用例需要超過1個增量才能成爲迴文,則程序會以某種方式進入無限循環。例如,如果我輸入100作爲測試用例,則輸出爲101.類似地,如果輸入908,則得到909作爲輸出。但是如果我輸入108,我不會得到111輸出。

請忍受我愚蠢的錯誤,我是Java編程新手。由於

import java.util.Scanner; 


class nextPalindrome { 

    public static void nextPalindromeGenerate(int n) 
    { 
     int flag=1;   
     int digit;   //to store the mod value 
     int rev=0;   //reverse of the number 
     int original;  //dummy to store the original number 

     if(n<10) 
     { System.out.println(n+1); //If number is single digit, next smallest palindrome is n+1 
      flag=0; 


     } 


     while(flag!=0) 
     { ++n; 
      original=n; 

      while(n>0)  //loop for reversing the number 
      { 
       digit=n%10; 
       rev=rev*10+digit; 
       n=n/10; 
      } 

      if(rev==original) //check if original equals the reverse(original) 
      { 
       System.out.println(rev); 
       flag=0; 


      } 

      else flag=1; 
     } 

    } 

    public static void main(String[] args) 
    { 

    @SuppressWarnings("resource") 
    Scanner sc=new Scanner(System.in); 




     int n=sc.nextInt(); 
     int[] palinList=new int[n]; 
     for(int i=0;i<n;i++) 
     { 

      palinList[i]=sc.nextInt();; 
     } 

     for(int j=0;j<n;j++) 
     { 
      nextPalindromeGenerate(palinList[j]); 

     } 
} 
} 

回答

0

你增加n到下一個整數,以測試爲迴文(!),它保存在origingal,然後垃圾n,看它是否是一個迴文。但是你不會爲下一次迭代重置n

+0

謝謝。這真的很有幫助。此外,我沒有重置數字,並在每次while循環開始時都進行轉動。現在該程序正在運行。 – ccg2k16

0

這個問題極其微不足道,只是將rev,digit和n重置爲有意義的值。工作方案如下:

import java.util.Scanner; 




class nextPalindrome { 

    public static void nextPalindromeGenerate(int n) 
    { 
     int flag=1;   
     int digit;   //to store the mod value 
     int rev=0;   //reverse of the number 
     int original;  //dummy to store the original number 

     if(n<10) 
     { System.out.println(n+1); //If number is single digit, next smallest palindrome is n+1 
      flag=0; 


     } 

     original=n; 
     while(flag!=0) 
     { rev=0;digit=0; 
      n=++original; 

      while(n>0)  //loop for reversing the number 
      { 
       digit=n%10; 
       rev=rev*10+digit; 
       n=n/10; 
      } 

      if(rev==original) //check if original equals the reverse(original) 
      { 
       System.out.println(original); 
       flag=0; 


      } 

      else flag=1; 
     } 

    } 

    public static void main(String[] args) 
    { 

    @SuppressWarnings("resource") 
    Scanner sc=new Scanner(System.in); 




     int n=sc.nextInt(); 
     int[] palinList=new int[n]; 
     for(int i=0;i<n;i++) 
     { 

      palinList[i]=sc.nextInt();; 
     } 

     for(int j=0;j<n;j++) 
     { 
      nextPalindromeGenerate(palinList[j]); 

     } 

} 
}