zoukankan      html  css  js  c++  java
  • PAT甲级——A1001A+BFormat

    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 −. 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

    很简单,数字转字符串即可
     1 #define _CRT_SECURE_NO_WARNINGS
     2 
     3 #include <iostream>
     4 #include <vector>
     5 #include <sstream>
     6 #include <string>
     7 #include <stack>
     8 
     9 using namespace std;
    10 
    11 int main()
    12 {
    13     int a, b,sum;
    14     string str;
    15     scanf("%d %d", &a, &b);
    16     sum = a + b;
    17     stringstream ss;
    18     ss << sum;
    19     ss >> str;
    20 
    21     ///此处可以通过sum/1000,然后转为字符串
    22     stack<string>res;
    23     int k;
    24     string s;
    25     for (k = str.length(); k > 3;k-=3)
    26     {    
    27         s.assign(str.begin() + k - 3, str.begin() + k);
    28         res.push(s);
    29         res.push(",");
    30     }
    31     s.assign(str.begin(), str.begin() + k);
    32     if (s == "-")
    33         res.pop();
    34     res.push(s);
    35     while (!res.empty())
    36     {
    37         cout << res.top();
    38         res.pop();
    39     }
    40     return 0;
    41 }

    更简洁点

     1 #include <iostream>
     2 using namespace std;
     3 int main() {
     4     int a, b;
     5     cin >> a >> b;
     6     string s = to_string(a + b);
     7     int len = s.length();
     8     for (int i = 0; i < len; i++) {
     9         cout << s[i];
    10         if (s[i] == '-') continue;
    11         if ((i + 1) % 3 == len % 3 && i != len - 1) cout << ",";
    12     }
    13     return 0;
    14 }
  • 相关阅读:
    浩然战法--黄金柱选股
    《含泪活着》主人公一一丁尚彪,叙述在日本当黑户口的危险经历,美国《世界日报》2017年3月16日连载
    Java8与JDK8和JDK1.8有什么区别?
    ThreadLocal
    什么是jsonp
    Java中比较对象大小的两种实现方式
    MySQL教程之concat以及group_concat的用法
    多级树形结构和sql查询实现
    mysql树形结构递归查询
    Maven配置教程
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11159598.html
Copyright © 2011-2022 走看看