算法筆記_181:歷屆試題 回文數字(Java)
阿新 • • 發佈:2017-05-05
else integer cti print alt 條件 ont 解決方案 test
本題要求你找到一些5位或6位的十進制數字。滿足如下要求:
該數字的各個數位之和等於輸入的整數。 輸入格式 一個正整數 n (10<n<100), 表示要求滿足的數位和。 輸出格式 若幹行,每行包含一個滿足要求的5位或6位整數。
數字按從小到大的順序排列。
如果沒有滿足條件的,輸出:-1 樣例輸入 44 樣例輸出 99899
499994
589985
598895
679976
688886
697796
769967
778877
787787
796697
859958
868868
877778
886688
895598
949949
958859
967769
976679
985589
994499 樣例輸入 60 樣例輸出 -1
目錄
1 問題描述
2 解決方案
1 問題描述
問題描述 觀察數字:12321,123321 都有一個共同的特征,無論從左到右讀還是從右向左讀,都是相同的。這樣的數字叫做:回文數字。本題要求你找到一些5位或6位的十進制數字。滿足如下要求:
該數字的各個數位之和等於輸入的整數。 輸入格式 一個正整數 n (10<n<100), 表示要求滿足的數位和。 輸出格式 若幹行,每行包含一個滿足要求的5位或6位整數。
數字按從小到大的順序排列。
如果沒有滿足條件的,輸出:-1 樣例輸入 44 樣例輸出 99899
499994
589985
598895
679976
688886
697796
769967
778877
787787
796697
859958
868868
877778
886688
895598
949949
958859
967769
976679
985589
994499 樣例輸入 60 樣例輸出 -1
2 解決方案
具體代碼如下:
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static int n; public void getResult() { ArrayList<Integer> result = new ArrayList<Integer>(); for(int i = 10000;i < 1000000;i++) { String temp = i + ""; if(temp.length() == 5) { if(temp.charAt(0) == temp.charAt(4) && temp.charAt(1) == temp.charAt(3)) {int num = i % 10 * 2 + i / 10 % 10 * 2 + i / 100 % 10; if(num == n) result.add(i); } } else if(temp.length() == 6) { if(temp.charAt(0) == temp.charAt(5) && temp.charAt(1) == temp.charAt(4) && temp.charAt(2) == temp.charAt(3)) { int num = i % 10 * 2 + i / 10 % 10 * 2 + i / 100 % 10 * 2; if(num == n) result.add(i); } } } if(result.size() == 0) System.out.println("-1"); else { Collections.sort(result); for(int i = 0;i < result.size();i++) System.out.println(result.get(i)); } } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); n = in.nextInt(); test.getResult(); } }
算法筆記_181:歷屆試題 回文數字(Java)