PAT (Advanced level) 1001 A+B Format (20 分)

版权声明:转载请附链接 https://blog.csdn.net/isunLt/article/details/83590766

1001 A+B Format (20 分)

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

代码

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
	int a, b;
	cin >> a >> b;
	int c = a + b;
	string sign = c < 0 ? "-" : "";
	c = fabs(c);
	string sumAbs = to_string(c);
	reverse(sumAbs.begin(), sumAbs.end());
	string result;
	for (int i = 0; i < sumAbs.size(); i++)
	{
		if (!i || i % 3) result += sumAbs[i]; //如果i不是0,或者i不能被3整除,直接加在后面
		else                                  //如果能被3整除, 先加一个","再把数字加在后面
		{
			result += ",";
			result += sumAbs[i];
		}
	}
	result += sign;                               //最后加上符号
	reverse(result.begin(), result.end());        //将结果倒转回来
	cout << result << endl;
	return 0;
}

思路

首先,题目说这里的a和b是绝对值小于106的整数,所以不用考虑大数加减的算法(C++ int类型一共32位,取值范围在 -231 ~ 231 之间),直接两数相加,判断并保存符号在sign字符串中,然后求绝对值,使用to_string函数转成string类型保存在sumAbs中,使用reverse函数将sumAbs倒转,分情况将值加在result后面,最后加上之前保存的符号sign,再倒转回来。

有两个坑

  1. 本来想用string.insert(size_t pos, const string& str) 把“, ”直接插入到字符串中间,但是因为插入后字符串变长了这样再找下标能被3整除的位置就会出错,使题目变麻烦。。。
    @[TOC](这里写自定义目录标题)
  2. 本来想把
			result += ",";
			result += sumAbs[i];

写成

			result += ("," + sumAbs[i]);

但是cout输出答案时发现答案变成了-99991而不是-999,991于是我发现这里有个细节,因为","是一个char,sumAbs[i]也是一个char 两个char类型相加并不是连接而是ASCII码相加,所以出错。
a = -1000000 b = 9
以上

猜你喜欢

转载自blog.csdn.net/isunLt/article/details/83590766