PAT 甲级测试题目 -- 1001 A+B Format

考研志向是浙大计算机专业,为了通过机试,打算写下 PAT 中甲级所有题目答案,思路和答案记录在此
题目网址
题目概述:
计算两数a, b之和,两数范围在 −106 ≤ a, b ≤ 10​6,输出的数据每三位用逗号隔开。
思路:
考虑到 int 为 4字节(32bit),完全 hold 住题目中的数据大小,因此此题的难点在于数字的规格输出。所以粗略的想法是将数字转换成字符串输出。
提交一(C++):

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

int times = 0;

string NumtoString(int resnum) {
	if (resnum < 0)
		resnum = -resnum;
	string str = "0000000";
	for (int i = 0; i < 6; i++) {
		str[i] = resnum % 10 + '0';
		resnum /= 10;
		times++;
		if (resnum == 0)
			return str;
	}
}

int main() {
	int a, b;
	int resnum;
	cin >> a >> b;
	resnum = a + b;

	string result = NumtoString(resnum);
	
	if (resnum < 0) 
		cout << "-";
	
	for (int i = times-1; i >= 0; i--) {
		cout << result[i];
		if (i % 3 == 0 && i != 0)
			cout << ",";
	}	
	return 0;
}

由于未使用C++自带的转换函数,自己写了一个,不过恰好也能更方便地输出数字。
对新手来说隐藏的坑点:
1.负数的取模运算
2.for 循环逻辑

编译器显示部分正确,因此开始思考特殊值
特殊值1:
-1000000 0
输出
-
代码中逻辑错误
函数中 for 循环上界出错
提交二(C++):

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

int times = 0;

string NumtoString(int resnum) {
	if (resnum < 0)
		resnum = -resnum;
	string str = "0000000";
				 
	for (int i = 0; i < 7; i++) {
		str[i] = resnum % 10 + '0';
		resnum /= 10;
		times++;
		if (resnum == 0)
			return str;
	}
}

int main() {
	int a, b;
	int resnum;
	cin >> a >> b;
	resnum = a + b;

	string result = NumtoString(resnum);
	
	if (resnum < 0) 
		cout << "-";
	
	for (int i = times-1; i >= 0; i--) {
		cout << result[i];
		if (i % 3 == 0 && i != 0)
			cout << ",";
	}
	
	return 0;
}

提交结果:
答案正确

原文地址:https://www.cnblogs.com/Breathmint/p/10262536.html