记录PAT刷题第一天
题目1001 A+B FormatCalculate 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 −1e6≤a,b≤1e6. 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
算法题解:
题目大意是进行a+b结果的输出,不过对于结果的输出有一定的格式要求,我们进行特定格式输出即可。
对于计算的结果我们通过C++11中的to_string方法,将计算结果转化为字符串形式,然后依次输出字符,在下标不等于len - 1且满足(i + 1) % 3 == len % 3 时,进行"," 的输出,对于-号直接输出!这道题属于细节题目,要看清样例输出的结果格式,进行特定输出即可!
c++代码:#include
#include
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
string s = to_string(a + b);
int len = s.length();
for(int i = 0; i < len; i ++)
{
cout << s[i];
if(s[i] == '-') continue;
if(i != len - 1 && (i + 1) % 3 == len % 3)
{
cout << ",";
}
}
return 0;
}
(注:第一次写博客,写的可能不好,不过也算迈出了第一步,加油!!希望自己可以坚持下去!)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)