andy6804tw
7/21/2016 - 4:56 AM

https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=959&mosmsg=Submission+received+

https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=959&mosmsg=Submission+received+with+ID+17705978

這題數字翻轉相加會爆所以要用long型態 還要注意1.當只輸入長度為1的數字印出相加然後跳出迴圈2.第一筆資料不做回文(palindrome)判斷

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		int n = Integer.parseInt(scn.nextLine());
		while (n-- != 0) {
			String str = scn.next();
			int i = 0, j = 1, count = 1;
			long tot = 0;
			while (true) {
				char s[] = str.toCharArray();//拆開成字元陣列做回文(palindrome)判斷
				if (s.length == 1 && count == 1) { //假如只有長度為一相加然後跳出迴圈
					tot = Long.parseLong(str) + Long.parseLong(str);
					break;
				}
				if (count > 1) {//假如是第一筆資料不做回文判斷
					for (i = 0, j = s.length - 1; i < j; i++, j--) {
						if (s[i] != s[j])
							break;
					}
				}
				if (i >= j) {//判斷回文成立跳出迴圈
					count--;
					break;
				}
				StringBuilder st = new StringBuilder();//字串翻轉
				st.append(str).reverse();
				String str2 = String.valueOf(st);//StringBuilder轉回String型態
				tot = Long.parseLong(str2) + Long.parseLong(str);//兩字串轉成Long型態相加
				str = String.valueOf(tot);//Long轉字串
				count++;
			}
			System.out.println(count + " " + tot);
		}
	}
		/* 
    題目:Q10018: Reverse and Add
    作者:1010
    時間:西元 2016 年 7 月 */
}