Algorithm/C++ BOJ
C++) [BOJ] 2935 소음
HSH12345
2023. 2. 19. 02:17
2935번: 소음
수업 시간에 떠드는 두 학생이 있다. 두 학생은 수업에 집중하는 대신에 글로벌 경제 위기에 대해서 토론하고 있었다. 토론이 점점 과열되면서 두 학생은 목소리를 높였고, 결국 선생님은 크게
www.acmicpc.net
#include <iostream>;
#include <string>;
using namespace std;
int main()
{
int a, b, ans;
char oper;
cin >> a >> oper >> b;
if (oper == '+') ans = a + b;
else if(oper == '*') ans = a * b;
cout << ans << "\n";
}
처음 제출한 답안, 문제의 조건 중 a 와 b는 100자리 수까지 입력될 수 있다고 하는데 떄문에, 연산의 결과가 C++의 정수 자료형으로는 표현할 수 없는 수가 나올 수 있다.
#include <iostream>;
#include<string>;
using namespace std;
int main()
{
string a, b, ans;
char oper;
cin >> a >> oper >> b;
if (oper == '+')
{
if (a.length() > b.length())
{
a.erase(a.length() - b.length(), a.length());
ans = a + b;
}
else if (a.length() == b.length())
{
a.erase(0, 1);
ans = "2" + a;
}
else
{
a.erase(b.length() - a.length(), b.length());
ans = b + a;
}
}
else if (oper == '*')
{
b.erase(0, 1);
ans = a + b;
}
cout << ans << "\n";
}
문제의 조건에 맞게 새로운 로직을 구성해봤는데 여기서 문제는 문자열의 길이를 구하는 length 함수가 해당 조건의 범위를 충족할 만큼 값을 표현할 수 없었다. -> 런타임에러 Out of Range
#include <iostream>;
using namespace std;
int main()
{
string a, b, ans;
char oper;
cin >> a >> oper >> b;
if (oper == '+')
{
if (a.size() > b.size())
{
a.erase(a.size() - b.size(), a.size());
ans = a + b;
}
else if (a.size() == b.size())
{
a.erase(a.begin());
ans = '2' + a;
}
else if (a.size() < b.size())
{
b.erase(b.size() - a.size(), b.size());
ans = b + a;
}
}
else if (oper == '*')
{
b.erase(b.begin());
ans = a + b;
}
cout << ans << "\n";
}
전부 size 함수로 변경해 해결할 수 있었다. length는 문자열의 길이를, size는 문자열이 메모리에 저장된 크기를 반환한다고 하는데 이 문제에서 어떠한 차이로 오답과 정답이 되는지 찾아봐야겠다.