今天开始刷PAT练习数据结构的基础。
原题链接
这道题的思路很清晰。即便是题目给出了数字范围,为了避免int类型(32位)溢出的可能,把位数扩展至long int(64)的长度。
- 先将两数相加取绝对值,赋值给变量 addT;如果 addT=0,返回字符串“0”;
- while循环逐步取 addT 的最后一个数(取模),存入字符串 relust;
- 对 addT 除以10 抛弃最后一个数字,并赋值给自己;
- 计数器 count 每 3 次添一个逗号;添完后归零重新计数;
- 退出循环再考虑符号问题;
给出代码:
#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;
}