PAT 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).ios

Inputgit

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

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

Sample Inputcode

-1000000 9orm

Sample Outputblog

-999,991three



題目意思:A+B求和,而後每三位爲一個單位加上一個「,」的格式輸出。
解題思路:轉換成字符串來遍歷會很方便,注意如果負數第一位負號也要佔位的,而且要求最後一位不能出現「,」,其實能夠看看遍歷到當前位時剩下的位數如果3的倍數,那麼就須要加「,」了。

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
    int a,b,len;
    int i;
    string str;
    cin>>a>>b;
    str=to_string(a+b);
    len=str.size();
    for(i=0;i<len;i++)
    {
        cout<<str[i];
        if(str[i]=='-')
        {
            continue;
        }
        if((len-i-1)%3==0&&i!=len-1)
        {
            cout<<",";
        }
    }
    return 0;
}
 
  

注意這裏的to_string是C++11裏面string中所包含的函數。ci

相關文章
相關標籤/搜索