PAT (Advanced Level) Practice 1001 A+B Format (20分)

PAT (Advanced Level) Practice 1001 A+B Format (20分)

1、试题描述:

PAT (Advanced Level) Practice 1001 A+B Format (20分)_第1张图片

2、试题解答:

#include 
#include 
using namespace std;
int main()
{
	int a, b;
	cin >> a;
	cin >> b;
	int sum = a + b;
	if (sum < 0){
		printf("-");
		sum = -sum;
	}
	string str = to_string(sum);
	for (int i = 0; i < str.size(); i++)
	{
		cout << str[i];
		
		// The only difficulty lies in this judgment conduction
		// (i + 1) % 3 == str.size() % 3 to add ","
		// i != str.size() - 1 To avoid output "," at the end.
		if ((i + 1) % 3 == str.size() % 3 && i != str.size() - 1)
		{
			cout << ",";
		}
	}
	cout << "" << endl;
	system("pause");
	return 0;
}

3、积累

一直用Java, 很少使用C++来做这种题目。

  1. string str = to_string(sum);
    使用的头文件是 , 然后可以使用 str[index]的方式进行元素访问。

  2. (i + 1) % 3 == str.size() % 3;
    这个判断条件有点意思。

你可能感兴趣的:(PAT-AL,PAT,算法,刷题,C++,1001)