文章目录
总题解目录
[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;
}

被折叠的 条评论
为什么被折叠?



