2014-12-09 2 views
0

나는 회문수 번호를 찾고 싶습니다. ArrayList 실제로 노력하고 있습니다. nth palindrome이지만 너무 느리게 작동합니까? arraylist없이 어떻게 할 수 있습니까? 또는 어떻게 더 잘할 수 있습니까?n 번째 팔린 드롬 번호 찾기

(1 -- is the first) 
(2 -- is the second) 
(3 -- is the third) 
..... 
(9 -- is the Ninth.) 
(11 -- is the 10th) 
(22-- is the 11th) 
(919---is the hundredth) 
.....so on 

코드 :

public static void main(String[] args) { 
    Scanner cin = new Scanner(System.in); 
    int num = Integer.parseInt(cin.nextLine()); 

    ArrayList<Integer> str = new ArrayList<Integer>(); 
    for (int i = 1; i <=10000000; i++) { 
     if(str.size()==10000){break;} 
     int a = i; 
     int b = inverse(a); 
     if (a == b) { 
      str.add(a); 
     } 

    } 
    do { 

     int y = str.get(num - 1); 
     System.out.println(y); 



    } while (num==0); 

} 

public static int inverse(int x) { 
    int inv = 0; 
    while (x > 0) { 
     inv = inv * 10 + x % 10; 
     x = x/10; 

    } 
    return inv; 
} 
} 
+1

대신'if (str.size() == num)'이란 무엇입니까? –

+2

이것은 수학 문제이며 프로그래밍 문제는 아닙니다. 모든 초기 palindromes을 찾을 필요없이 n 번째 palindrome을 찾는 방법을 찾으십시오. – Eric

+0

결코 이상하거나 심지어 –

답변

0

그냥 i 번째 회문의 수를 유지하는 카운터 변수를 사용합니다.

public static void main(String[] args){ 
    // TODO Auto-generated method stub 

    Scanner cin = new Scanner(System.in); 
    int num = Integer.parseInt(cin.nextLine()); 
    int p = 0; 


    for (int i = 1; i <=10000000; i++) { 
     if(p==10000){break;} 
     int a = i; 
     int b = inverse(a); 
     if (a == b) { 
      p++; 
      if(p==num) 
      { 
       System.out.println(a); 
       break; 
      } 
     } 

    } 


}