【PAT】1001. A+B Format

http://pat.zju.edu.cn/contests/pat-a-practise/1001

此题花费了很长时间,做了几次都是说超时,网上找了个答案找到毛病,while(true)是绝对不能用的,while(cin>>a>>b)可以用。

#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
    int a,b,sum,n,i;
    
        n=1,i=1;
        cin>>a>>b;
        sum=a+b;
        //cout<<sum<<endl;
        bool isneg=false;
        if(sum<0)
        {
            isneg=true;
            sum=0-sum;//不用abs()函数了
        }
        string str;        
        
        while(sum)
        {
            char ch='0'+sum%10;
            sum/=10;
            if(i%4==0)
            {
                str.push_back(',');
                i=1;
            }
            str.push_back(ch);        
            i++;       
        }
        reverse(str.begin(),str.end());
        if(isneg)
        {
            cout<<'-';                
        }        
        cout<<str<<endl;
    
        
    system("PAUSE");
    return EXIT_SUCCESS;
}


搞定之后还是有个测试点通不过,于是又找了个答案:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
	long a,b,c;
	int i,flag;
	bool is_positive;
	char result[9];

	while(cin>>a>>b)
	{
		c = a+b;
		if( c>0 ) 
			is_positive = true;
		else 
			is_positive = false;
	
		flag = 0;  		
		if(abs(c) >= 1000){
			c = abs(c);  //取绝对值
			for( i=0; c>0; i++){
				result[i] = c%10 + '0';  //数字转换成字符
				c = c/10;
				if(flag == 2 && c != 0 )   
				{
					i++;
					result[i] = ',';   //每三个加一个逗号  
					flag = 0;
				}
				else
					flag++;				
			}
			if( !is_positive )  //结果为负数时
			{
				result[i] = '-';
				cout<<result[i];
			}

			i--;  //i指向第一个数字
			for(; i>=0; i--){
				cout<<result[i];
			}					
			cout<<endl;
		}
		else
		{
			cout<<c<<endl;
		}
	}
	return 0;
}

还有个更加简单的做法:

#include<stdio.h>
int main()
{
  int a,b;
  int sum;
  while(scanf("%d%d\n",&a,&b) != EOF){
        sum = a+b;
	if(sum < 0){
	printf("-");
	sum = -sum;
	}
    if(sum>=1000000){
        printf("%d,%03d,%03d\n",sum/1000000, (sum/1000)%1000, sum%1000);
    }
    else if(sum >= 1000){
        printf("%d,%03d\n",sum/1000,sum%1000);
    } else{
        printf("%d\n", sum);
    }
  }
  return 0;
}
个人感觉有点取巧,但是解决的思路也很不错、精巧吧!


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值