1. 程式人生 > >PAT甲級1001

PAT甲級1001

-c text cal must 不一定 math tex bin ups

【題目】

1001 A+B Format (20 point(s))

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 ?10?6??a,b10?6??. 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

【題意】

輸入兩個整數a,b然後讓其相加並將其的和每3個用“,”隔開

【註意】

1.這個逗號隔開的形式是比如 : 1111+1111 那麽應該輸出的結果是2,222而不是222,2(因為我起初這麽想然後錯了........)

2.還要註意形如 :

  • 111,
  • ,111
  • 111,

     

 1 #include<iostream>
 2 #include<cmath>
 3 #include<stack>
 4 using namespace std;
 5 int main() {
 6     int a,b;
 7     while (cin >> a >> b) {
 8         int ans = a + b;
 9         
10         //處理負號 
11         if (ans < 0
) cout << "-"; 12 ans = abs(ans); 13 14 //用棧來存儲 15 stack<int> s; 16 int cnt=0; 17 18 //如果ans是0就直接輸出了吧 19 if (ans == 0) { 20 cout << 0 << endl; 21 continue; 22 } 23 24 while (ans) { 25 s.push(ans % 10); 26 ans /= 10; 27 } 28 int mk; //標記前面第幾個digit會有逗號用的,因為這邊不一定是第三個 29 int array[100000]; 30 while (!s.empty()) { 31 array[++cnt] = s.top(); 32 s.pop(); 33 } 34 35 mk = cnt % 3; 36 for (int i = 1; i<=cnt; ++i) { 37 //為了防止最後會多出個逗號就這麽來了,本來還想再用個cnt2來判斷 38 if ((i-mk-1>0)&&(!((i-mk-1)%3))) cout<<","; 39 else if (i-1==mk&&i-1>0)cout<<","; 40 cout << array[i]; 41 } 42 cout << endl; 43 } 44 }

PAT甲級1001