zoukankan      html  css  js  c++  java
  • PAT 甲级 1001 A+B Format

    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 106​​a,b106​​. 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 << "
    ";
      }
      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; }
  • 相关阅读:
    struts2 错误:Dispatcher initialization failed java.lang.RuntimeException
    JavaScript如何实现拖放功能
    Javascript异步执行时要小心的变量作用域
    Javascript异步编程
    Origin null is not allowed by Access-Control-Allow-Origin
    eclipse spket插件 错误 Syntax error on token "(", FunctionExpressionHeader expected after this
    EL--Expression Language
    [Swift]LeetCode820. 单词的压缩编码 | Short Encoding of Words
    [Swift]LeetCode879. 盈利计划 | Profitable Schemes
    [Swift]LeetCode878. 第 N 个神奇数字 | Nth Magical Number
  • 原文地址:https://www.cnblogs.com/sunrisepeak/p/9745419.html
Copyright © 2011-2022 走看看