1001 A+B Format (20 分)
Posted vanish丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1001 A+B Format (20 分)相关的知识,希望对你有一定的参考价值。
1. 题目
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
2. 题意
将两个数a和b相加,并按照从低位到高位,三位一逗号形式输出。
3. 思路——简单模拟
- a和b相加后以字符串形式存储,从字符串尾部开始遍历,每三位插入一个逗号。
- 边界条件:
- 位数刚为3的倍数时:例123,此时遍历到1时,计数cnt刚好为3,但是因为i为0,所以条件不满足,不会插入新的逗号。
- 负数:例-123,此时遍历到1时,计数刚好为3,虽然此时i为1,但是判断sum[i - 1]为负号,不满足条件,不会插入新的逗号。
4. 代码
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
string sum = to_string(a + b);
int cnt = 0; // 计数每三位需添加一个逗号
for (int i = sum.size() - 1; i >= 0; --i)
{
cnt++;
// 这里中间的条件为i不为0,防止sum[i-1]溢出
if (cnt % 3 == 0 && i && sum[i - 1] != \'-\')
{
sum.insert(i, 1, \',\'); // 满足三位一个逗号,并将逗号插入
cnt = 0; // 插入逗号后,计数清零
}
}
cout << sum <<endl;
return 0;
}
PAT 甲级 1001 A+B Format (20)(20 分)
1001 A+B Format (20)(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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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
注意几个输出点:-991 991 1001 -1001
1 #include<iostream> 2 #include <sstream> 3 #include<string> 4 #include<stack> 5 #include<typeinfo> 6 7 using namespace std; 8 9 int main() 10 { 11 int a,b,flag=0,temp=0; 12 13 cin>>a>>b; 14 15 a+=b; 16 17 if(a<0) 18 { 19 flag=1; 20 cout<<"-"; 21 } 22 23 stringstream ss; 24 ss<<a; 25 26 string str=ss.str(); 27 28 stack<char> s; 29 30 for(int i=str.length()-1;i>=flag;--i) 31 { 32 s.push(str[i]); 33 ++temp; 34 35 if(temp%3==0 && i-1>=flag) 36 s.push(‘,‘); 37 } 38 39 while(!s.empty()) 40 { 41 cout<<s.top(); 42 s.pop(); 43 } 44 45 cout<<endl; 46 47 return 0; 48 }
以上是关于1001 A+B Format (20 分)的主要内容,如果未能解决你的问题,请参考以下文章