[PAT-A] 1001 A+B Format

字符串、模拟

Hyplus目录

1 原题

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 \le a,b \le 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

代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
栈限制 8192 KB


2 代码示例

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] strs = reader.readLine().split(" ");
        long a = Long.parseLong(strs[0]);
        long b = Long.parseLong(strs[1]);
        long c = a + b;

        if (c == 0) {
            System.out.println(0);
        } else {
            if (c < 0) {
                System.out.print("-");
                c *= -1;
            }

            StringBuilder res = new StringBuilder();
            int i = 1;
            while (c > 0) {
                res.append(c % 10);
                c /= 10;
                if (c > 0 && i % 3 == 0) {
                    res.append(",");
                }
                i++;
            }

            for (i = res.length() - 1; i >= 0; i--) {
                System.out.print(res.charAt(i));
            }
        }
    }
}

C++

#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>

using namespace std;

int main() {
    int a, b;
    cin >> a >> b;

    int c = a + b;
    if (c < 0) cout << "-";
    string str = to_string(abs(c));

    stack<char> stk;
    for (int i = (int) str.size() - 1, cnt = 0; i >= 0; i--) {
        if (cnt == 3) {
            stk.push(',');
            cnt = 0;
        }
        stk.push(str[i]);
        cnt++;
    }

    while (!stk.empty()) {
        cout << stk.top();
        stk.pop();
    }

    return 0;
}

发表评论