回文数 找第n个回文数

来源:互联网 发布:怎么添加usb001端口 编辑:程序博客网 时间:2024/05/20 23:39
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;        }    }
0 0