1. 程式人生 > >【PAT-A】1001. A+B Format 寫題記錄

【PAT-A】1001. A+B Format 寫題記錄

思路:

結果c預先判斷,等於零則直接輸出,小於零則先輸出“-”,再按大於零處理。

之後用棧來處理,如果陣列長度是3的倍數且大於3,就輸出逗號。最後3位單獨處理,直接輸出。

#include <cstdio>
#include <stack>
using namespace std;
int main(){
	int a,b,c;
	scanf("%d%d",&a,&b);
	c = a+b;  //得出結果 
	
	if (c<0){   //小於零輸出負號,再變成正數 
		printf("-");
		c = -1*c;
	} else if(c == 0){  //等於零則直接輸出,結束程式 
		printf("0");
		return 0;
	} 
	
	stack<int> S;  //用棧 
	while(c>0){  //取尾數入棧 
		S.push(c % 10);
		c /= 10;
	}
	
	while(!S.empty()){  //一直輸出,直到棧空,前面數字和最後3位數字分開處理 
		if(S.size()>3){  / 
			printf("%d",S.top());
			S.pop();
			if (S.size()%3 == 0) printf(",");  //先輸出數字,若位數是3的倍數就輸出逗號 
		} else{
			printf("%d",S.top()); //位數小於等於則3位直接輸出 
			S.pop();		
		}
	}
	return 0;
}