1001. A+B Format (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
题目链接http://www.patest.cn/contests/pat-a-practise/1001
c++实现
#include <iostream>
#include <iomanip>
#include <stack>//栈头文件
using namespace std;
int main()
{
int a, b, sum;
cin >> a >> b;
sum = a + b;
stack<int> stk;//构造一个栈
if (sum == 0)
{
stk.push(0);
}
else if (sum < 0)
{
cout << "-";
sum = -sum;
}
while (sum != 0)
{
stk.push(sum % 1000);//取最后三位(百位十位个位)的部分入栈
sum = sum/1000;
}
cout << stk.top();
stk.pop();
while (!stk.empty ())
{
cout << ',' << setfill('0') << setw(3) << stk.top();//setfill('0')空余处填充0,setw(3)设置输出宽度3
stk.pop();
}
//system("pause");
return 0;
}
源代码链接
https://github.com/varvelworld/PAT-Advanced-Level-Practise/blob/master/1001/1001.cpp
==========
2015.7.18
我的java
import java.util.*;
import java.math.*;
import static java.lang.System.*;
public class Main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner cin=new Scanner(System.in);
int greater_0=0,count=0;//greater_0控制添加','号,count控制添加','
BigInteger a=cin.nextBigInteger();//大整型a
BigInteger b=cin.nextBigInteger();//大整型a
BigInteger sum=a.add(b);//计算a+b
String result="";//保存添加','后的数字
greater_0=sum.compareTo(BigInteger.valueOf(0));//判断sum>=0
if(greater_0==-1)//若sum<0,则将sum转换为正整数
{
sum=sum.multiply(BigInteger.valueOf(-1));
out.print("-");//输出sum前面的符号
}
String s=sum.toString();//将大整形sum转换为字符串
for(int i=s.length()-1;i>=0;i--)
{
result=result+String.valueOf(s.charAt(i));//将sum的字符分别添加进字符串result
count++;//控制添加','号
if(count%3==0&&i!=0)//除sum第一个位置外,其它位置每满3个字符则添加','
result=result+",";
}
for(int j=result.length()-1;j>=0;j--)//倒序输出result
{
out.print(result.charAt(j));
}
}
}