1001 A+B Format

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 −10​6​​≤a,b≤10​6​​. 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

题目大意:给你两个数a,b让你求出a+b的值,并且把这个值按每三个数字用一个‘,’来分隔得格式输出结果,主要是格式问题。  但要注意当两个数相加结果为0的情况,我就忽视了这个点,然后第4个测试点一直过不了,找了很久才发现。负号一开始先不用考虑,最后添加上就行,一开始可以将相加的结果取绝对值,对绝对值进行处理。

accept code:

#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;

string str="",temp="",revtemp="";

string InttoChar(int s)//将整型转化为字符串型的函数
{
	while(s!=0){
		int r=s%10;
		s=s/10;
		temp+=(r+'0');
	}
	return temp;
}

string charreverse(string s){//对转化后的字符串进行翻转处理的函数
	revtemp="";
	for(int i=s.length()-1;i>=0;i--){
		revtemp+=s[i];
	}
	return revtemp;
}

string compactchar(string s){//对反转后的字符串格式化的函数
	int count=0;
	for(int j=s.length()-1;j>=0;j--){
		if(count==3){
			count=0;
			str+=',';
			j+=1;
		}
		else{
			str+=s[j];
			count++;
		}
	}
	str=charreverse(str);
	return str;
}

int main()
{
	int sum=0;
	string s1,s2,s3;
	int a,b;
	cin>>a>>b;
	sum=a+b;
	if(sum==0)
	{
		cout<<0<<endl;
	}
	else if(sum<0){//判断是否加“-”
		sum=abs(sum);
		s1=InttoChar(sum);
		s2=charreverse(s1);
		s3=compactchar(s2);
		cout<<'-'<<s3<<endl;
	}
	else{
		s1=InttoChar(sum);
		s2=charreverse(s1);
		s3=compactchar(s2);
		cout<<s3<<endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.无名之辈

1毛也是爱~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值