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
思路:如果我们从整数这个思路来求的话,我们需要知道这个数的长度,通过求模,得到长度,然后对这个数从高位到低位求,总长度减去当前所处位置是不是3的倍数,。这样比较麻烦,有没有求出这个数将其转为字符串的函数呢?有的 ,这篇博文写了一些转化的方式:https://blog.csdn.net/qq_40511966/article/details/81010855。如果把这个数换成字符串就很好处理了,<=三位的直接输出,超过三位的总长度减去当前所处位置是不是3的倍数,是则输出一个逗号(如,总长7(1234567),当前位置0,很明显不是3的倍数,当前位置1,7-1是3 的倍数,故而输出一个,需要注意的是0也是3的倍数)。由于我代码的原因,我还需要判断i==0也不能输出,why?如果总长9位,它首先输出一个,。
c++
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
int a,b,sum;
string s;
cin >> a >> b;
stringstream ss;
sum = a+b;
if(sum < 0)
{
sum = sum*(-1);
cout << "-";
}
ss << sum;
ss >> s;
if(s.length()<=3)
cout << s << endl;
else
{
for(int i = 0;i < s.length();++i)
{
if((s.length()-i)%3 == 0 && i != s.length()-1 && i != 0)
cout << ",";
cout << s[i];
}
cout << endl;
}
return 0;
}
Java(仅提供写法,不提供oj版)
public class Main{
public static void getResult(String sum){
int len = sum.length();
char[] str = sum.toCharArray();
for(int i = 0;i < len;++i)
{
if((len-i)%3 == 0 && i != len-1 && i != 0)
{
System.out.print(",");
}
System.out.print(str[i]);
}
}
public static void main(String[] args){
int a,b;
Scanner in = new Scanner(System.in);
a = in.nextInt();
b= in.nextInt();
Integer sum = a+b;
if(sum < 0)
{
sum *= -1;
System.out.print("-");
}
getResult(sum.toString());
}
}