1001 A+B Format

1001. A+B Format (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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

这题我的做法是字符串处理。一开始理解错了题意,以为是从前往后每出三位数字就出一个逗号,比如:1000输出为100,0,实际上应该是1,000
然后20分只拿到14分= =(SB样例根本看不出来啊)后来把输出逗号的判断由

cnt%3==0;

改为

(length-cnt)%3==0;length是结果字符串的长度

然后就过了。。。。下面贴代码:

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
  int a,b;
  char result[100]={0};//保留结果(其实开7个就足够了)
  cin>>a>>b;
  int sum=a+b,j=0;
  if(sum<0)cout<<'-';//小于0
  int sum1=fabs(sum);//取绝对值
  if(sum==0)cout<<0<<endl;//对于0情况的特判
  else
  {
    while(sum1)//将结果转为字符串
   {
     result[j++]=(sum1%10+'0');
     sum1/=10;
   }
   int cnt=0;//统计输出了多少位
   for(int i=j-1;i>=0;i--)
   {
     if((j-cnt)%3==0&&cnt)//输出逗号的情况
       cout<<',';
     cnt++;//加一位
     cout<<result[i];
   }
   cout<<endl;
  }
}

然而其实我这个方法复杂了,因为题中的数据范围只是正负一百万,也就是最多只有两个逗号输出。所以只需要三个if条件句输出即可==。但是我这种方法还是可以处理更高位数的对不对?理直气壮.JPG ,下面放方法二的代码:

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
  int a,b;
  cin>>a>>b;
  int sum=a+b;
  if(sum<0)cout<<'-';
  sum=fabs(sum);
  if(sum>=1000000)
  //注意控制字段长度,比如001的输出,不足补‘0’;
    cout<<sum/1000000<<','<<setfill('0')<<setw(3)<<sum/1000%1000<<','<<setfill('0')<<setw(3)<<sum%1000<<endl;
  else if(sum>=1000)
   cout<<sum/1000<<','<<setfill('0')<<setw(3)<<sum%1000<<endl;
  else cout<<sum<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值