码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1001 A+B Format

时间:2018-10-06 00:04:54      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:ott   解释   air   逗号   alc   ber   blank   地址   rate   

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,b10?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的和,其 和 要按照格式化形式输出,且要能测试多组数据(简单列出几种和的情况):

1
122
1,234
-1
-123,123

 


 思路与AC代码:

 

 此题AC的关键就是在于如何解决格式化输出的问题,而这使我想到了用栈的思想很符合这题的要求,把a+b的和从低位压入栈中,最后在出栈从而判断在哪位数后输出逗号。

本题注意事项:

1.怎么在一个多位数中插入逗号:这里采用栈或数组的思想进行分解
2.对第一个逗号的输出进行判断
3.注意和分正负情况
4.最好一个数后面不用再输出逗号了

 

 

AC代码1:

#include<iostream>
using namespace std;
int main()
{
  int a, b, c[10],top;
  while(cin >> a >> b)
  {
    top = -1;            //初始化top
    a = a + b;
    if(a < 0)            //取a+b和的绝对值
    {
        cout << "-";
        a = -a;
    }
    if(a == 0)            //和为0的情况
        cout << "0";
    while(a)            //对和进行求余逐个入栈
    {
        c[++top] = a % 10;
        a = a/10;
    }
    int length = top + 1;
    int k = length%3;    //用于记录第一逗号的标记(例如是五位数会在第二位输出,4位数是第一个输出)
    while(top >= 0)        //循环出栈
    {
        cout << c[top--];    
        if(length > 3 && top >= 2)        //判断和小于等于三位数不用输出逗号,和确保最后一个逗号输出是在倒数第三个数输出时输出
            if(length - top - 1== k || ((length - top - k - 1)%3 == 0))    //左边是判断第一个逗号输出,右边是判断剩余逗号输出(就是对3求余)
                cout << ",";
    }
    cout << "\n";
  }
  return 0;
}

 

AC代码2:由于给出了范围就可以直接写出范围内的情况,代码比较简洁高效,且易于看懂这里就不多解释了。当然我是用上面代码AC的哭笑脸。。。

#include<iostream>
using namespace std;
int main()
{
int a,b; cin>>a>>b; int c=a+b; if(c<0){cout<<-;c=-c;} if(c>=1000000) { printf("%d,%03d,%03d",c/1000000,c%1000000/1000,c%1000); }else if(c>=1000){ printf("%d,%03d",c/1000,c%1000); }else{ printf("%d",c); } return 0; }

 

 

 

 

PAT 1001 A+B Format

标签:ott   解释   air   逗号   alc   ber   blank   地址   rate   

原文地址:https://www.cnblogs.com/sunrisepeak/p/9745419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!