標籤:沒有 com ons 目錄 筆記 技術分享 數位 color logs
目錄
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)