[code] PTA 1001 A+B Format DAY001

题目在这里插入图片描述

题意解读

数据量int范围。求A+B的和,输出按三位逗号分隔格式输出。

思路

主要思路A+B数字的和转换为string类型再进行格式操作。

  • 思路1 从后向前输出,但是在处理的时候要注意整除的情况下不用再在前面加逗号的情况。eg. 100000 -> 100,000。我采用的是字符串的插入处理,看到网上还有其他人采用压栈的方式处理感觉也不错。
  • 思路2 从前往后处理。找到第一个加逗号的位置,之后都是+3跳着打点的过程。同样要注意最后的时候不用加逗号的情况。

C++ code

// method 1 by myself
#include <iostream>
#include <string>

int main()
{
    int a, b;
    std::cin >> a >> b;
    std::string result = std::to_string(a+b);

    // 1. check >= 4 digits
    int times = 0;
    int left = 0;
    int lenth = result.size();
    if (result[0] != '-' ) {
        if (lenth >= 4) {
            times = lenth / 3;
            if (lenth % 3 == 0) {
                times = times - 1;
                left = 3;
            } else {
                left = lenth % 3;
            }
        }
    } else {
        if (lenth >= 5) {
            times = (lenth - 1 ) / 3;
            if ((lenth - 1 ) % 3 == 0) {
                times = times - 1;
                left = 3 + 1;
            } else {
                left = (lenth - 1) % 3 + 1;
            }

        }
    }

    // 2. format
    if (times != 0) {
        std::string tmp = "";
        for (int i = 1; i <= times; ++i) {
            tmp.insert(0, result.substr(lenth-3*i,3));
            tmp.insert(0,1,',');
        }
        tmp.insert(0, result.substr(0,left));
        result = tmp;
    }


    std::cout << result << std::endl;

    return 0;
}

// method 2: 压栈
#include <iostream>
#include <iomanip>
#include <stack>

using namespace std;

int main()
{
    long  int a;
    long  int b;
    long  int c;
    long  int d;
    stack<long int> stk;
    cin >> a >> b;  
    c = a + b;
    string str;
    while(c>999||c<-999)
    {
        d = abs(c % 1000);//取最后三位
        c = c / 1000;//去掉最后三位
        stk.push(d);
    }
    cout << c;
    while (!stk.empty())
    {
        cout << "," << setfill('0') << setw(3) <<stk.top();
        stk.pop();
    }
    return 0;
}

// method 3: 直接从前往后处理
#include <iostream>
using namespace std;
int main() {
    int a, b;
    cin >> a >> b;
    string s = to_string(a + b);
    int len = s.length();
    for (int i = 0; i < len; i++) {
        cout << s[i];
        if (s[i] == '-') continue;
        if ((i + 1) % 3 == len % 3 && i != len - 1) cout << ","; // 找到第一个打逗号的地方,后续都是+3 +3跳着打逗号的过程
    }
    return 0;
}

小结

  1. 情况注意考虑完全,这里忘记考虑整除不用加逗号的情况。
  2. 可以多看看其他人的解题思路,拓展一下自己的思维方式。

立个flag,本次重新刷题是自己开启了一个新挑战,code 100天。可能后期会是做项目的code,我争取能分享的都写写博客记录一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值