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 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
#include <iostream>
#include <vector>
using namespace std;
int main(){
int a,b,c,ans=0;
cin>>a>>b;
c=a+b;
if(c<0){
ans=1;
c=-c;
}
vector<int>v;
if(c==0)
v.push_back(0);
while(c!=0){
v.push_back(c%10);
c/=10;
}
vector<int>::reverse_iterator iter;
if(ans){
cout<<"-";
}
int j=v.size()%3;
int jj=0;
for(iter=v.rbegin(); iter<v.rend(); ++iter){ //将结果倒序遍历,
cout<<*iter;
++jj;
if(jj==j && j<v.size() || jj%3==j && jj<v.size()){ //在特定位置输出‘,’
cout<<",";
}
}
return 0;
}
Python3 代码如下:
a , b = input().split(' ')
s = int(a) + int(b)
if s < 0:
s1=str(-s)
print('-',end='')
else:
s1=str(s)
for i in range(1,len(s1) + 1):
print(s1[i-1] ,',' if i%3==len(s1)%3 and i!=len(s1) else '', sep='', end='')