1001. A+B Format (20)

2017-03-13  本文已影响0人  _SANTU_

时间限制
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

AC代码:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main(int argc, const char * argv[]) {
    int a, b, sum;
    cin >> a >> b;
    sum = a + b;
    
    string str;
    str = to_string(sum);
    if(str[0] == '-') {
        cout << '-';
        str.erase(0,1);
    }
    reverse(str.begin(), str.end() );
    int len = (int)str.size();
    for(int i = 3; i < len; i += 3) {
        str.insert(i, ",");
        i++;
        len++;
    }
    reverse(str.begin(), str.end() );
    cout << str << endl;
    return 0;
}

string字符串操作:

提供另一种解法

//
//  main.cpp
//  pat
//
//  Created by yaojies on 16/8/16.
//  Copyright © 2016年 yaojies. All rights reserved.
//

#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, const char * argv[]) {
    int numA, numB, result;
    void functionOfPrint(int result);
    cin >> numA >> numB;
    result = numA + numB;
    //print "-" if result < 0
    if(result<0){
        cout << "-";
        result = -result;
    }
    functionOfPrint(result);
    cout << endl;
    return 0;
}
void functionOfPrint(int result){
    if(result>999){
        functionOfPrint(result/1000);
        cout << ",";
        cout << setfill('0')<<setw(3) << result%1000;
    }else{
        cout << result;
    }
}

上一篇下一篇

猜你喜欢

热点阅读