PAT (Advanced Level) Practise 1001. A+B Format (20)

来源:互联网 发布:js中html方法 编辑:程序博客网 时间:2024/04/29 20:18

1001. A+B Format (20)
时间限制: 400 ms
内存限制: 65536 kB
代码长度限制: 16000 B
判题程序:Standard


  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.

Examples

Input -1000000 9 Output -999,991

 
Notes
  

作者
  CHEN, Yue

  题意不难理解,用三位分节法表示a+b的和,解决方法是不断用n%10取n的个位,并用n/10舍去个位,直到n为0。由于从最低位开始处理,要将处理结果反过来显示。注意和为0的显示。

#include <iostream>#include <algorithm>#include <map>#include <vector>#include <functional>#include <string>#include <cstring>#include <queue>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <sstream>#include <iomanip>using namespace std;#define IOS ios_base::sync_with_stdio(false)#define TIE std::cin.tie(0)#define MIN2(a,b) (a<b?a:b)#define MIN3(a,b) (a<b?(a<c?a:c):(b<c?b:c))#define MAX2(a,b) (a>b?a:b)#define MAX3(a,b,c)  (a>b?(a>c?a:c):(b>c?b:c))typedef long long LL;typedef unsigned long long ULL;const int INF = 0x3f3f3f3f;const double PI = 4.0*atan(1.0);const double esp = 0.000001;int a, b, n, p, cnt;bool nflag;char s[20];int main(){    while (scanf("%d%d", &a, &b) == 2){        n = a + b;        cnt = p = 0;        if (n == 0){ printf("0\n"); continue; }        if (n > 0)  nflag = false;        else{ nflag = true; n = -n; }        while (n != 0){            cnt++;            if (cnt == 4){                cnt = 0;                s[p++] = ',';            }            else{                s[p++] = n % 10 + '0';                n /= 10;            }        }        if (nflag) s[p++] = '-';        while (p) printf("%c", s[--p]);        printf("\n");    }}
0 0