某校2018专硕编程题-回文数
原创
©著作权归作者所有:来自51CTO博客作者图图是只猫的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目
编程题:输入一组正整数,判断输入的数字是否为回文数,是则输出该数。输入-1时结束。提示:若一个正整数(首位不为0),从左向右读与从右向左读是一样的,则称作回文数,例如1,11,121,,1221,12321 等都是回文数。
例如:输入 121 1212 22 2,则输出结果为 121 22 2
提示:不需要输入全部数据之后再统一处理,例如输入1212时,121以已输出。
分析
- 转字符串倒序和原数相等
- 数学算法
有关回文数的各种解法可移步:回文数的各种实现
Java实现
字符串
public static void test02(){
Scanner sc = new Scanner(System.in);
while (true){
Integer a = sc.nextInt();
if (a == -1) break;
StringBuffer s = new StringBuffer(a.toString());
if (s.reverse().toString().equals(a.toString())){
System.out.print(a);
}
}
}
数学算法
public static void test02_(){
Scanner sc = new Scanner(System.in);
while(true){
int a = sc.nextInt();
if (a == -1) break;
int b = a,c = 0;
while (b > 0){
c = c*10 + b%10;
b /= 10;
}
if (c == a) System.out.println(a);
}
}