[CodeUp] #3022-큰 수 뺄셈(스택)

chrmqgozj·2022년 1월 21일
0

CodeUp

목록 보기
17/48
#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main(){
	string a,b;
	stack<char> s1,s2;
	stack<int> ans;
	cin >> a >> b;
	int change = 0;
	
	if(a.size()<b.size()){
		string s = a;
		a = b;
		b = s;
		change++;
	}
	else if(a.size()==b.size()){
		int cnt = 0;
		for(int i=0;i<a.size();i++){
			if(a[i]>b[i]){
				break;
			}
			else if(a[i]<b[i]){
				cnt++;
				break;
			}
		}
		if(cnt!=0){
			string s = a;
			a = b;
			b = s;
			change++;
		}
	}
	
	for(int i=0;i<a.size();i++){
		s1.push(a[i]);
	}
	for(int i=0;i<b.size();i++){
		s2.push(b[i]);
	}

	int extra = 0;
	while(!s1.empty() && !s2.empty()){
		int x1 = s1.top()-'0';
		int x2 = s2.top()-'0';
		s1.pop();
		s2.pop();
		if(x1-x2-extra>=0){
			// cout << x1-x2-extra << "\n";
			ans.push(x1-x2-extra);
			extra = 0;
		}
		else{
			// cout << x1-x2-extra+10 << "\n";
			ans.push(x1-x2-extra+10);
			extra = 1;
		}
	}

	while(!s1.empty()){
		int x = s1.top()-'0';
		s1.pop();
		if(x-extra<0){
			// cout << x-extra+10 << "\n";
			ans.push(x-extra+10);
			extra = 1;
		}
		else{
			// cout << x-extra << "\n";
			ans.push(x-extra);
			extra = 0;
		}
	}
	
	if(change !=0 ){
		cout << '-';
	}
	
	int chk = 0;
	
	while(!ans.empty()){
		if(ans.top()!=0){
			chk++;
		}
		if(chk!=0){
			cout << ans.top();
		}
		ans.pop();
	}
	if(chk == 0){
		cout << chk;
	}

}

0개의 댓글

관련 채용 정보