PAT 1001. A+B Format (20)(字符串转换)

原创 2016年08月31日 09:27:08

题目

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
提交代码

解题思路

  • 1.先将和转话为字符串,然后利用stack从后往前加上,最后在从堆顶依次输出。

AC代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<stack>
using namespace std;

int main(int argc, char *argv[])
{
    ios_base::sync_with_stdio(false);
    int a,b,sum;
    cin >> a >> b;
    sum = a + b;
    if (sum<0) {
        //printf("-");
        cout<<"-";
    }
    //将和转化为字符串
    sum = abs(sum);
    string str;
    stringstream ss;
    ss << sum;
    ss >> str;
    int len =str.length();
    //利用stack加入,
    stack<char> keep;
    int cnt = 0;
    while (len--) {
        cnt++;
        keep.push(str[len]);
        if (cnt%3==0) {
            keep.push(',');
        }
    }
    //依次输出
    char out = keep.top();
    if (out==',') {
        keep.pop();
    }
    while (!keep.empty()) {
        char out = keep.top();
        cout << out;
        keep.pop();
    }
    cout << endl;
    return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

PAT-A 1001. A+B Format (20)

PAT-A 1001. A+B Format (20) 逗号输出有坑……

PAT1001. A+B Format(20)

最近开始每天做一道PAT练手,下面是PAT1001的题目。 Calculate a + b and output the sum in standard format -- that is, th...
  • wtrnash
  • wtrnash
  • 2017年03月27日 20:41
  • 109

[PAT]1001. A+B Format (20)

Calculate a + b and output the sum in standard format -- that is, the digits must be separated into ...
  • fnzsjt
  • fnzsjt
  • 2014年07月21日 15:26
  • 517

PAT:A1001. A+B Format (20/20)

Calculate a + b and output the sum in standard format -- that is, the digits must be separated into ...

Pat 1001. A+B format

此题为两个数求和后进行格式化输出,因为没有超出Integer的表示范围,可以直接整数求和。 思路如下:import java.io.BufferedReader; import java.io.IOE...

PAT_1001: A+B Format

Calculate a + b and output the sum in standard format -- that is, the digits must be separated into ...

PAT 1001 A+B Format

1001 A+B Format

PAT 1001 A+B Format 简洁代码的思考

PAT 1001 A+B Format 简洁代码的思考

1001. A+B Format (20) C++

问题描述: Calculate a + b and output the sum in standard format – that is, the digits must be separated ...

1001. A+B Format (20)

1001. A+B Format (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B ...
  • fynjy
  • fynjy
  • 2015年07月06日 13:35
  • 230
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:PAT 1001. A+B Format (20)(字符串转换)
举报原因:
原因补充:

(最多只允许输入30个字)