【PAT甲级题解记录】1001 A+B Format (20 分)

前言

Problem:1001 A+B Format (20 分)

Tags:整型转字符串 字符串截断 (c++)

Difficulty:剧情模式 想流点汗 想流点血 死而无憾

Address:1001 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).

两个整数相加,每三位加一’,'输出。

解题思路

  1. 题目本身简单,但需要技巧提速,对于这种问题转化为字符串会方便很多,利用string to_string(int val)转化;

  2. 负数的话首先输出负号,再利用字符串截断函数string.substr()去掉负号的影响;

  3. 接下来得到的字符串长度为 l e n len len,下标为 i i i,那么在下标为 i = l e n − 3 k i=len-3k i=len3k 的字符输出前输出 ‘,’ 即可,也就是 (len-i)%3==0 时(除了 i = 0 i=0 i=0)。

参考代码

#include<iostream>

using namespace std;

void solution_1001() {
    int a, b;
    std::cin >> a >> b;
    string str = to_string(a + b);
    if (str[0] == '-') {
        cout << '-';
        str = str.substr(1);
    }
    int len = str.length();
    for (int i = 0; i < len; i++) {
        if ((len - i) % 3 == 0 && i != 0) {
            cout << ',';
        }
        cout << str[i];
    }
    cout << endl;
}

int main() {
    solution_1002();
    return 0;
}

总结

  1. 整型转字符串函数原型:

    string to_string(int val);
    
  2. 字符串截断:

    string sub1 = s.substr(pos);  // 表示以下标pos开始截断到结尾
    
    string sub2 = s.substr(pos,n);  // 表示以下标pos开始截断长度为n位
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值