迴文數 找第n個迴文數

package HW;

public class NthHuiWenNum {
    //數位指個位,十位,百位,千位。。。
        public static void main(String[] args) {
            int input = 1201; //Integer.parseInt(args[0]);
            long res = find(input);
            System.out.println("res:" + res);

        }

        static long find(int index) {
            int count = 0;            
            int number = 9;                        //記錄數位上的迴文數,如個位迴文數爲9
            int w = 0;                            //記錄數位

            long half;                            //保存迴文數的左半邊的結果
            long h = 1;                            //迴文數的左半邊的起始基數
            long res;                            //結果

            while(true) {
                if(w > 0 && w%2 == 0) {            //每進兩個數位,迴文數乘以10
                    number *= 10;
                }
                w++;                            //數位加一
                if(count + number > index)        //迴文數大於查找的回數,跳出
                    break;

                count += number;                //迴文數加上當前數位上的迴文數
            }

            index -= count;                        //在當前數位上的位置。如w=5,index=50,則萬位上的第50個迴文數是我們所求

            for(int i = 0; i < (w-1) / 2; i++) {    //求迴文數的左半邊的基數,如迴文數在萬位上,則爲100
                h *= 10;
            }

            half = h + index;                        //迴文數的左半邊,如100 + 50 = 150

            res = half;

            if(w%2 != 0)                            //如果爲奇數,則中間那個數不必算入右半邊了!
                half /=10;

            while(half != 0) {                        //拼接回文數
                res = res *10 + half % 10;
                half /= 10;
            }

            return res;
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章