PAT甲级1001 A+B Format

今天开始刷PAT练习数据结构的基础。
原题链接

这道题的思路很清晰。即便是题目给出了数字范围,为了避免int类型(32位)溢出的可能,把位数扩展至long int(64)的长度。

  1. 先将两数相加取绝对值,赋值给变量 addT;如果 addT=0,返回字符串“0”;
  2. while循环逐步取 addT 的最后一个数(取模),存入字符串 relust;
  3. 对 addT 除以10 抛弃最后一个数字,并赋值给自己;
  4. 计数器 count 每 3 次添一个逗号;添完后归零重新计数;
  5. 退出循环再考虑符号问题;

给出代码:

#include<iostream>
#include<string>
using namespace std;

string dealwith(long int x,long int y){
    string relust="";
    long int addT = x + y;
    addT = abs(addT);
    if(addT == 0) return "0";
    int count = 0;
    while(addT>0){
        count++;
        relust = to_string(addT % 10) + relust;
        if(count==3 && addT/10 != 0){
            relust = ',' + relust;
            count = 0;
        }
        addT = addT/10;
    }
    if(x+y < 0 ){
        relust = '-' + relust;
    }
    return relust;
}

int main(){
    long int x,y;
    cin >> x >> y;
    cout << dealwith(x, y) << endl;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值