題目
程式設計題:輸入一組正整數,判斷輸入的數字是否為回文數,是則輸出該數。輸入-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);
}
}