1001. A+B Format (20)

2015 ワード

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,99
   :
#include <iostream>
#include <string>
using namespace std;
int n[7];
char c[10];
string intConvertString(int a) {
    string str;
    int i, j = 0, k = 0;
    int temp = 0;
    for(i=0; i<7; i++) {
        n[i] = a%10;
        a /=10;
        if(n[i]!=0) {
            temp = i + 1;
        }
    }
    for(i=0; i<temp; i++) {
        c[j++] = n[i]+'0';
        if((i+1)%3 == 0&&i+1!=temp) {
            c[j++] = ',';
        }
    }
    for(i=0; i<j/2; i++) {
        temp = c[i];
        c[i] = c[j-i-1];
        c[j-i-1] = temp;
    }
    return c;
}
int main() {
    int a, b, sum;
    while(cin>>a>>b) {
        sum = a + b;
        if(sum > 0) {
            cout<<intConvertString(sum)<<endl; 
        } else if(sum < 0){
            cout<<"-"<<intConvertString(-sum)<<endl;
        } else {
            cout<<"0"<<endl;
        }
    }
    return 0;
}


   :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    
    int a,b;
    cin>>a>>b;
    int c = a + b;
    stringstream strStream;  
    strStream<<c;            //int string   !
    string s = strStream.str();

    for(int i = s.size() - 3; i > 0 && s[i - 1] != '-'; i -= 3)
        s.insert(i, ",");

    cout<<s<<endl;
}