PAT-甲级-1001 A+B Format C++
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 −106≤a,b≤106. 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
题意:
题目意思是计算c=a+b,但是要按照规范输出c,从末位开始,每隔三个输出一个逗号。
分析:
水题。关键在于处理第一个逗号出现的位置。c可能是正数、可能是负数,首先判断是否需要输出-,然后统一处理符号位后面的数字。后面的数字关键在于判断输出逗号的间隔interval,如果数字位数>3,interval需要额外处理,即用%的方式来判断第一个逗号出现的位置,后面剩余的数字位数为3的整数倍,可以固定输出逗号;如果数字位数<3,不需要输出逗号。
代码:
//
// Created by yaodong on 2023/7/5.
//
#include "iostream"
#include "cstring"
int main() {
int a, b;
std::cin >> a >> b;
int sum = a + b;
std::string sumString = std::to_string(a + b);
// std::cout << sumString.length() << std::endl;
int len = sumString.length();
if (sum < 0) {
printf("-");
sumString = sumString.substr(1, len - 1);
len = sumString.length();
}
int interval = len > 3 ? (len % 3 == 0 ? 3 : len % 3) : len;
int i = 0;
while (i < len) {
if (interval-- > 0)
std::cout << sumString[i++];
else {
interval = 2;
std::cout << "," << sumString[i++];
}
}
// printf("%s", sumString.c_str());
}