문제
https://www.acmicpc.net/problem/2935
풀이
The operands will be powers of 10 with no more than 100 digits.(피연산자는 정수 100개를 넘지 않는 길이의 10의 거듭제곱이다)
를 읽고 A와 B를 정수형 말고 문자열로 취급했다.
ans 문자열에 A와 B 중 길이가 긴 문자열을 복사하고, 다른 문자열을
1) 더하는 경우: ans 문자열의 longer-shorter 인덱스의 숫자를 1로 변경한다.
2) 곱하는 경우: 복사해둔 ans 문자열의 뒤에 필요한 만큼 0을 추가한다.
이렇게만 구현했는데 틀렸다고 나와서 더 생각해보니, 1+1, 100+100 등 동일한 수를 더하는 경우 2, 200처럼 ans[0]이 2가 되어야 했다.
소스코드
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
char A[101] = {};
char B[101] = {};
char ans[101] = {};
char operationType;
cin >> A >> operationType >> B;
int Alen = strlen(A); // 길이
int Blen = strlen(B);
int longer, shorter;
longer = (Alen>=Blen)? Alen: Blen;
shorter = (Alen<=Blen)? Alen: Blen;
if(Alen > Blen) memcpy(ans, A, longer);
else memcpy(ans, B, longer);
// int i;
// for(i=0; i < longer; i++){
// if(i==0) ans[i] = '1';
// else ans[i] = '0';
// }
// ans[longer] = '\0';
if(operationType == '+')
{
if(longer == shorter) ans[0] = '2';
else ans[longer-shorter] = '1';
}
if(operationType == '*')
{
for(int i=1; i<shorter; i++){
ans[longer] = '0';
ans[longer+1] = '\0';
longer++;
}
}
cout << ans << endl;
return 0;
}
발전
주어진 테스트케이스 외에 더 많은 경우를 생각해보고 돌려보자.
코드가 뭔가 더 깔끔해질 수 있을 것 같은데 ,, 나중에 코드 정리해봐야겠다.
'Problem Solving' 카테고리의 다른 글
[백준/BOJ] 5717. Og (C++) (0) | 2024.05.14 |
---|---|
[백준/BOJ] 10102. Vote Count (C++) (0) | 2024.05.14 |
[백준/BOJ] 10214. Baseball (C++) (0) | 2024.05.11 |
[백준/BOJ] 2476. 주사위 게임 (C++) (0) | 2024.05.10 |
[백준/BOJ] 1934. 최소공배수 (C++) (0) | 2024.05.10 |