1001 A+B Format (20 分)
【PAT甲级】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<cstdio>
#include<cstring>
int main(){
long long a, b;//两个数相加之后用int也许会溢出
scanf("%lld%lld",&a,&b);
long long sum = a + b;
char z[10];//用来存放求和后的数,一个个放进去
int len = 0, flag = 0;
long long sum1 = sum < 0 ? -sum : sum;//将负的和转换为正的,当然也可以用绝对值函数
do{
z[len++] = '0' + sum1 % 10;
if(len % 3 == 0) flag++;//用来记录需要添加多少个标点
sum1 = sum1 / 10;
}while(sum1 != 0);
z[len] = '\0';
for(int i = 0; i < len / 2; i++){
int temp = z[i];
z[i] = z[len - 1 - i];
z[len - 1 - i] = temp;
}
if(sum < 0) printf("-");//如果和是负数,那么我们先把符号输出
for(int i = 0; i < len + flag;i++){
if(len - i != 0 && (len - i) % 3 == 0 && i != 0) printf(",");//因为标点是从后算起的,所以用len-i,但是注意无论是第一位数字前面还是最后一位数字后面都不应该有逗号
printf("%c",z[i]);一个个输出
}
return 0;
}
版本二:
日期:2022/2/27
#include<iostream>
using namespace std;
int main(){
long long a , b , sum;
int z[20];
cin >> a >> b;
sum = a + b;//sum表示数字a与b的和
if(sum < 0){
cout << '-';
sum = -sum;
}
int i = 0,ans = sum;
do{
z[i++] = ans%10;
ans /= 10;//将sum降位
}while(ans>0);
if(i<=3) cout << sum;
else{
for(int j = i - 1; j >= 0; j--){//高位优先输出
if((j+1)%3==0&&j!=(i-1)) cout << ',';
cout<< z[j];
}
}
return 0;
}
版本三:
日期:2022/2/27
和版本二几乎一直,仅仅使用vector
来代替静态数组z[20]
,顺便复习一下vector
的相关操作
#include<iostream>
#include<vector>
using namespace std;
int main(){
long long a , b , sum;
vector<int> z;
cin >> a >> b;
sum = a + b;//sum表示数字a与b的和
if(sum < 0){
cout << '-';
sum *= -1;//变号
}
do{
z.push_back(sum % 10);
sum /= 10;//将sum降位
}while(sum>0);
for(int j = z.size() - 1; j >= 0; j--){//高位优先输出
if((j+1)%3==0&&j!=(z.size()-1)) cout << ',';
cout<< z[j];
}
return 0;
}