[PAT-Advanced] A1001 A+B Format (20)

总题解目录

[PAT- Advanced Level] 甲级题解目录(Advanced Level)

A1001 A+B Format (20point(s))

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

Analysis

  • 给出a和b,计算a+b的值,输出要求为每三个数字需要有一个“,”隔开。
  • 这道题很贴心的在题目中就给出了数据的范围,显然不论加减都在int的范围中,所以我们可以暂时不用考虑int数据边界的特殊情况
  • 注意特判结果为零的情况

C++ Code1

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <stack>
using namespace std;
stack<int> st;

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    a = a + b;
    b = abs(a);
    while(b != 0){
        st.push(b % 10);
        b /= 10;
    }
    if(a < 0) printf("-");
    else if(a == 0){        // 特判结果为0的情况
        printf("0\n");
        return 0;
    }
    for(b = st.size(); st.empty() != 1;){
        printf("%d", st.top());
        st.pop();
        // 若剩下的数字个数为三的倍数,则输出“,”
        if(--b % 3 == 0 && st.empty() != 1){
            printf(",");
        }
    }
    return 0;
}

C++ Code2

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>

using namespace std;

string format(int a){
    stringstream ss;
    ss << a;
    string result = ss.str();

    int str_len = result.size();	// 字符串长度 
    int num_len = result.size();	// 数字长度,不包括符号
    if(a < 0) num_len -= 1;			// 如果是负数,显然数字长度=字符串长度-1
    for(int i = 3; i < num_len; i++){	// 注意i的初始值和遍历范围,是这个方法解这道题的注意点,不懂的小伙伴可以拿一张纸推一下
        if(i % 3 == 0){
            result.insert((str_len-i), ",");
        }
    }

    return result;
}

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    
    cout << format(a + b);
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值