본문 바로가기

백준/C++

[C++] 백준 1357번 - 뒤집힌 덧셈

728x90

 

문제 1357번

https://www.acmicpc.net/problem/1357

 

string타입으로 입력받은 값을 reverse로 뒤집어준다. 각각을 더하기 위해 stoi를 통해 int타입으로 변경해준다. 더한 값을 int타입 변수에 저장하고 해당 값을 또 뒤집기 위해 to_string을 사용하여 string 타입으로 변환시킨다. reverse로 뒤집은 후 최종값을 stoi로 int타입으로 만들고 출력해준다. 여기서 int타입으로 변환시키는 이유는 string타입으로 한다면 10같은 숫자가 최종값일 때 뒤집으면 01이 되므로 0을 없애기 위한 것이다.

 

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
	string x, y, s_sum;
	int sum;
	cin >> x >> y;

	reverse(x.begin(), x.end());
	reverse(y.begin(), y.end());
	
	sum = stoi(x) + stoi(y);

	s_sum = to_string(sum);
	reverse(s_sum.begin(), s_sum.end());

	cout << stoi(s_sum);
	return 0;
}

 

728x90