PAT题解-A1001 A+B Format (20分)

题目

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

分类

简单数值计算、数值输出

题意说明

计算两个带符号整数的和,结果每三位加一个逗号(少于四位不加)。两数取值范围为10^-6 到10^6。

思路分析

  1. 题中两加数及二者之和都在int范围内,因此可用int类型接收两加数。
  2. 考虑每三位输出一个逗号,可以先计算出和,若小于零,则输出负号。结果取绝对值,使用模运算循环取结果的后三位,如果原数大于1000,则输出一个逗号。
  3. 因为取模运算得到的数是从低位开始的,而输出时需要从高位输出,可以用递归或者栈,实现反向输出。
  4. 也可以将数值当作字符串来处理,实现从高位到低位输出。

参考代码

方法1: 使用STL 栈

#include<cstdio>
#include<stack>

using namespace std;

void output(int a) {
    int tmp;
    stack<int> s;
    while (a > 0) {
        tmp = a % 1000;
        s.push(tmp);
        a /= 1000;
    }
    //结果为 0 时,没有数据入栈,此时需要特殊处理
    //否则当栈为空时,输出 s.top() 将提示“段错误”
    if(!s.empty()){
        printf("%d", s.top());
        s.pop();
    }else{
        printf("0");
        return;
    }
    while (!s.empty()) {
        //注意此处输出格式,逗号后面不足3位的要用0补足
        printf(",%03d", s.top());
        s.pop();
    }
}

int main() {
    int a, b;
    scanf("%d%d", &a, &b);
    a = a + b;
    if (a < 0) {
        printf("-");
        a = -a;
    }
    output(a);
    return 0;
}

方法二:使用递归

#include<cstdio>

void output(int a) {
    //数值小于1000时直接输出
    if (a < 1000) {
        printf("%d", a);
        return;
    } else {
        //数值大于1000时,先输出高位,再输出低位
        output(a / 1000);
        printf(",%03d", a % 1000);
    }
}

int main() {
    int a, b;
    scanf("%d%d", &a, &b);
    a = a + b;
    if (a < 0) {
        printf("-");
        a = -a;
    }
    output(a);
    return 0;
}

方法三:使用字符串操作

#include<cstdio>
#include <string>
using namespace std;
int main() {
    int a, b;
    scanf("%d%d", &a, &b);
    a = a + b;
    if (a < 0) {
        printf("-");
        a = -a;
    }
    string str = to_string(a);
    int len = str.length();
    for (int i = 0; i < len ; ++i) {
        //注意此处输出的是字符,格式用"%c",不要用"%d"
        printf("%c", str[i]);
        //从后往前每三位有一个逗号,末位不能是逗号
        if(i != len - 1 && (len - i - 1) % 3 == 0){
            printf(",");
        }
    }
    return 0;
}
发布了5 篇原创文章 · 获赞 0 · 访问量 769

猜你喜欢

转载自blog.csdn.net/qq_36382924/article/details/104068161