PAT甲级1001. A+B Format (20)
2017-08-24 10:56
483 查看
题目链接
https://www.patest.cn/contests/pat-a-practise/1001Calculate 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
思路分析
1.也就是输入两个数a和b,把a+b的和按照银行标准输出出来,每三位输出一个逗号2.考虑特殊情况比如 a+b = 0可以直接输出
3.把a+b和放在字符数组中,判断下标j满足条件输出逗号
代码
#include<iostream>using namespace std;
int main()
{
int a,b;
int c[100000];//用来倒序保存sum的每一位
cin>>a>>b;
int sum = a+b;
int t = 1;
if(sum < 0)
t = -1;
int i = 1;
int k = t*sum;//保证sum绝对值为正
while(k)//倒序保存sum
{
c[i] = k%10 ;
i++;
k = k/10;
}//此时sum一共有i-1位
if(sum < 0)//sum < 0 先输出-号
cout<<"-";
if(sum == 0) //考虑特殊情况 这也是一个测试点 一开始这个情况没考虑到
cout<<sum;
for(int j = i-1 ;j >= 1;j--)
{
if(j%3 == 0 && j!=i-1)//判断条件,当j为3的倍数且j不是i-1(第1位)输出,
cout<<",";
cout<<c[j];
}
return 0;
}
相关文章推荐
- PAT甲级-1001. A+B Format (20)逗号分隔
- PAT甲级 1001. A+B Format (20)
- PAT甲级 1001. A+B Format (20) 题目翻译与答案
- PAT甲级-1001. A+B Format (20)
- 浙江大学PAT_甲级_1001. A+B Format (20)
- PAT甲级1001. A+B Format (20)
- 【PAT甲级】1001. A+B Format (20)
- PAT 甲级1001. A+B Format (20)
- PAT甲级 1001. A+B Format (20)
- PAT - 甲级 - 1001. A+B Format (20)(字符串处理)
- [PAT甲级]1001. A+B Format (20)(AB和的标准输出)
- PAT甲级1001. A+B Format(20)
- PAT甲级.1001. A+B Format (20)
- 1001. A+B Format (20)-PAT甲级真题
- 【PAT甲级】1001. A+B Format (20)
- PAT甲级1001. A+B Format (20)
- PAT(甲级)1001. A+B Format (20)
- PAT甲级 1001. A+B Format (20)--两种方法
- 【PAT甲级】【C】1001. A+B Format (20)
- PAT甲级1001. A+B Format (20)解题报告