PAT (Advanced Level) Practice1001 A+B Format (20 分)(Java實現)

Problem Description

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 106a,b106−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

代碼示例(Java實現)

import java.util.Scanner;

/**
 * @author snowflake
 * @create-date 2019-07-17 23:19
 */
public class Main {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int sum = cin.nextInt() + cin.nextInt();
        // 取出符號位
        String sign = sum < 0 ? "-" : "";
        // 將數字轉化爲絕對值
        sum = Math.abs(sum);
        // 三位數及其一下
        if (sum < 1000) {
            System.out.println(sign + sum);
        } else {
        	// 將數字轉化爲字符串
            String str = sum + "";
            StringBuilder result = new StringBuilder();
            // 從右往左進行操作,每次移動三位
            for (int i = 0; i < str.length(); i += 3) {
            	// 如果剩餘的字符串還剩餘三位以上
                if (i + 3 < str.length()) {
                    result.insert(0, ",").insert(0, str.substring(str.length() - i - 3, str.length() - i));
                } else {
                    result.insert(0, ",").insert(0, str.substring(0, str.length() - i));
                }
            }
            // 結果要補上符號位
            System.out.println(sign + result.substring(0, result.length() - 1));
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章