1001 A+B Format (20point(s))(Java和C++)

文章目录

    • Java版
    • C++版

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≤106​​. 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

一开始做题的时候搞错了一个点,导致测试点一半正确,一半错误:就是从前往后每3个数出一个逗号。就像给的测试用例一样,但是这种方法只对字符串长度是3的整数倍的sum有效,要改成从后往前每3个数输出一个逗号
用一个特殊情况举例:
1000000+1000000=2000000
1001 A+B Format (20point(s))(Java和C++)_第1张图片

Java版

//20分
import java.io.*;
import java.math.BigInteger;

public class Main {
    public static void main(String[] args) throws IOException {
        //定义输入
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        //输入两个整数
        String[] str = bf.readLine().split("\\s+");
        //将输入的字符串转化为BigInteger类型
        BigInteger a = new BigInteger(str[0]);
        BigInteger b = new BigInteger(str[1]);
        //计算两个整数加和并转化为String类型
        String sum = a.add(b) + "";

//如果结果是负数,输出“-”,之后将字符串中的“-”去掉
        if (sum.charAt(0) == '-') {
            System.out.print("-");
            sum = sum.substring(1);
        }
        //遍历新字符串
        for (int i = 0; i < sum.length(); i++) {
            System.out.print(sum.charAt(i));
            //(i + 1) % 3 == sum.length() % 3是用来判断逗号要加的位置
            //(i != sum.length() - 1))用来保证输出的最后一位不输出逗号
            if ((i + 1) % 3 == sum.length() % 3 && (i != sum.length() - 1)) {
                System.out.print(",");
            }
            continue;
        }
    }
}

C++版

//参考柳神代码
//没想到思路和我的一样  
#include 
#include

using namespace std;

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    string s = to_string(a + b);
    for (int i = 0; i < s.length(); i++) {
        cout << s[i];
        if (s[i] == '-')
            continue;
        if ((i + 1) % 3 == s.length() % 3 && i != s.length() - 1)
            cout << ",";
    }
    return 0;
}

你可能感兴趣的:(PAT_Advanced)