PAT 甲级 1001 1001 A+B Format (20 分) 我的解法+别人的解法

原PAT网站用户可在 https://patest.cn/bind_old_pat_user 页面绑定至拼题A账号。绑定后,原PAT网站的提交将被合并至拼题A网站用户的对应题目集中。

 

返回

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 −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

 

我的解法:

 

大体思想:把两个数相加,结果一位一位的转化为字符,在转换为字符的过程中添加逗号

具体看代码:

#include<iostream>
#include<cstring>
#include<cstdio> 
#include<cmath>
using namespace std;
int main()
{
	int a,b;
	while(~scanf("%d %d",&a,&b))
	{
		
	    string tem;
		int c=a+b;
		int t=c;
		int i=0;
		while(t/10!=0)    // 判断是否能 对10取余 
		{
			tem+=(abs(t%10)+'0');   //数字转换为字符, 这个地方要加绝对值,否则,负数对10取余是负数,会影响结果 
			i++;
			if(i==3)
			{
				tem+=',';
				i=0;
			}
			t/=10;
		}
		tem+=(abs(t%10)+'0');   // 对 最后一位进行处理 
		if(c<0)   //对负数进行处理 
		tem+='-';
		for(i=tem.length()-1;i>=0;i--)    // 逆序输出 
		printf("%c",tem[i]);     
		printf("\n");
	}
	return 0;
 } 

别人的代码:

用了输出流

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    int a,b,ans;
    string str;
    ostringstream stream;
    cin>>a>>b;
    ans=a+b;
    stream<<ans;    ///向stream写入数据
    str=stream.str();///返回stream所保存的string拷贝
    int len=str.size();
    if(ans<0)   // 对负数进行处理
    {
        cout<<"-";
        len--;
        str=str.substr(1,len);
    }
    for(int i=len-3; i>0; i-=3)   // 每隔三位插入一个逗号
    {
        str.insert(i,",");
    }
    cout<<str<<endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值