⬆︎
×

[PAT-A] 1001 A+B Format

字符串、模拟

Hyplus目录

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;
}

发表评论