題目出自:PAT | 計算機程序設計能力考試(https://www.patest.cn/)
Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10^6
≤a,b≤10^6
. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
計算a+b並以標準格式輸出和——也就是說,數字必須用逗號分隔成三組(除非少於四位)。
輸入規格:每個輸入文件包含一個測試用例。每種情況都包含一對整數a和b,其中10^6≤a,b≤10^6。這些數字用空格隔開。
輸出規範:對於每個測試用例,您應該在一行中輸出a和b的和。總和必須用標準格式寫。
本人思路如下:
- 將a和b進行加法運算得到一個數值sum
- 判斷sum是負數還是非負數。
- 如果是非負數,將sum轉化為字符串,用for循環和String.valueOf()方法遍歷字符串,同時定義一個變量k,用於記錄for循環的次數,每進行3次循環,就輸出一個“,"。當k=3時,剛好輸出最後一個數字,則不輸出","。
- 如果是負數,則先輸出一個“-”,接下來的步驟與第3一致。
本人代碼如下:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); int result = sum(a, b); display(result); } public static int sum(int a, int b) { return a+b; } public static void display(int sum) { if (sum >= 0) { String s = String.valueOf(sum); int k = 0; for (int i=0; i測試結果如下:
總結:我不知道我的代碼出了什麼問題,只有部分正確,我嘗試提交了幾次,都是一樣的結果,可以推測的是,系統它早就設置好了數據,可能是比較鑽牛角的數字?我真的想不到。