1. 程式人生 > >PAT 1001 A+B Format

PAT 1001 A+B Format

ios baseline ets 逗號 unless pat calculate cat 絕對值

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

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兩個數(占一行),輸出和a+b的和,其 和 要按照格式化形式輸出,且要能測試多組數據(簡單列出幾種和的情況):

1
122
1,234
-1
-123,123


思路與AC代碼:

此題AC的關鍵就是在於如何解決格式化輸出的問題,而這使我想到了用棧的思想很符合這題的要求,把a+b的和從低位壓入棧中,最後在出棧從而判斷在哪位數後輸出逗號。

本題註意事項:

1.怎麽在一個多位數中插入逗號:這裏采用棧或數組的思想進行分解
2.對第一個逗號的輸出進行判斷
3.註意和分正負情況
4.最好一個數後面不用再輸出逗號了

AC代碼1:

#include<iostream>
using namespace std;
int main()
{
  int a, b, c[10],top;
  
while(cin >> a >> b) { top = -1; //初始化top a = a + b; if(a < 0) //取a+b和的絕對值 { cout << "-"; a = -a; } if(a == 0) //和為0的情況 cout << "0"; while(a) //對和進行求余逐個入棧 { c[++top] = a % 10; a = a/10; } int length = top + 1; int k = length%3; //用於記錄第一逗號的標記(例如是五位數會在第二位輸出,4位數是第一個輸出) while(top >= 0) //循環出棧 { cout << c[top--]; if(length > 3 && top >= 2) //判斷和小於等於三位數不用輸出逗號,和確保最後一個逗號輸出是在倒數第三個數輸出時輸出 if(length - top - 1== k || ((length - top - k - 1)%3 == 0)) //左邊是判斷第一個逗號輸出,右邊是判斷剩余逗號輸出(就是對3求余) cout << ","; } cout << "\n"; } return 0; }

AC代碼2:由於給出了範圍就可以直接寫出範圍內的情況,代碼比較簡潔高效,且易於看懂這裏就不多解釋了。當然我是用上面代碼AC的哭笑臉。。。

#include<iostream>
using namespace std;
int main()
{
int a,b; cin>>a>>b; int c=a+b; if(c<0){cout<<-;c=-c;} if(c>=1000000) { printf("%d,%03d,%03d",c/1000000,c%1000000/1000,c%1000); }else if(c>=1000){ printf("%d,%03d",c/1000,c%1000); }else{ printf("%d",c); } return 0; }

PAT 1001 A+B Format