문제 링크입니다: https://www.acmicpc.net/problem/15353
15353번: 큰 수 A+B (2)
C++17, C11, C99, C++98, C++11, C++14, C99 (Clang), C++98 (Clang), C++11 (Clang), C++14 (Clang), C11 (Clang), C++17 (Clang)
www.acmicpc.net
주어진 숫자가 최대 만 자리이기 때문에 long long 자료형으로도 풀 수 없는 문제였습니다.
따라서 문자열을 통해 덧셈을 직접 구현해야 하는 문제였습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <algorithm> | |
using namespace std; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
string A, B; | |
cin >> A >> B; | |
string result = ""; | |
reverse(A.begin(), A.end()); | |
reverse(B.begin(), B.end()); | |
int carry = 0; | |
for (int i = 0; i < min(A.length(), B.length()); i++) | |
{ | |
int sum = (A[i] - '0') + (B[i] - '0') + carry; | |
carry = 0; | |
if (sum >= 10) | |
{ | |
sum -= 10; | |
carry = 1; | |
} | |
result += to_string(sum); | |
} | |
for (int i = min(A.length(), B.length()); i < A.length(); i++) | |
{ | |
int sum = (A[i] - '0') + carry; | |
carry = 0; | |
if (sum >= 10) | |
{ | |
sum -= 10; | |
carry = 1; | |
} | |
result += to_string(sum); | |
} | |
for (int i = min(A.length(), B.length()); i < B.length(); i++) | |
{ | |
int sum = (B[i] - '0') + carry; | |
carry = 0; | |
if (sum >= 10) | |
{ | |
sum -= 10; | |
carry = 1; | |
} | |
result += to_string(sum); | |
} | |
if (carry) | |
{ | |
result += "1"; | |
} | |
reverse(result.begin(), result.end()); | |
cout << result << "\n"; | |
return 0; | |
} |

개발환경:Visual Studio 2022
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 14729번 칠무해 (0) | 2024.04.03 |
---|---|
백준 15926번 현욱은 괄호왕이야!! (1) | 2024.03.31 |
백준 13244번 Tree (0) | 2024.03.31 |
백준 14405번 피카츄 (0) | 2024.03.31 |
백준 14391번 종이 조각 (0) | 2024.03.31 |