找到第n个Palindrome数字

时间:2014-12-09 22:10:12

标签: java palindrome

我想找到第n个回文编号,我尝试ArrayList实际工作并找到nth回文但工作太慢我怎么能没有arraylist?或者我怎样才能做得更好?

(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 个答案:

答案 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;
            }
        }

    }


}