![[백준 / BOJ] 10757번 큰 수 A + B (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FpBZRK%2FbtrJk2nkUnQ%2Fb97RJ84Ony5QKukrgAZlm0%2Fimg.png)
[백준 / BOJ] 10757번 큰 수 A + B (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 4. 5. 17:11
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/10757
10757번: 큰 수 A+B
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
www.acmicpc.net
문제

문제 풀이
어떤 방법을 사용해도 정수형으로는 풀 수 없는 문제이다. 그러므로 char 배열을 이용하거나 string을 이용해야 한다.
둘 다 맥락은 비슷하지만 string으로 풀어보았다.
C++ 상세 풀이
C++ 풀이 펼쳐보기
for (i = 0; i < len; ++i) {
tmp = carry;
carry = false;
if (i < A.size()) tmp += A[A.size() - i - 1] - '0';
if (i < B.size()) tmp += B[B.size() - i - 1] - '0';
if (tmp >= 10) {
carry = true;
tmp -= 10;
}
v.insert(v.begin(), tmp);
}
if (carry) v.insert(v.begin(), 1);
입력받은 두 값중 더 길이가 긴 값을 기준으로 잡고, carry를 이용해 올림 표시를 해 주며 이어나가면 된다. 덧셈 연산과 똑같다.
Python 상세 풀이
Python 풀이 펼쳐보기
파이썬은 int로도 받아진다.
A, B = map(int, input().split())
print(A + B)
C++ 코드 전문
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 <algorithm> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
int main() { | |
string A, B; | |
cin >> A >> B; | |
int len = max(A.size(), B.size()); | |
vector<int> v; | |
bool carry = false; | |
int i, tmp; | |
for (i = 0; i < len; ++i) { | |
tmp = carry; | |
carry = false; | |
if (i < A.size()) tmp += A[A.size() - i - 1] - '0'; | |
if (i < B.size()) tmp += B[B.size() - i - 1] - '0'; | |
if (tmp >= 10) { | |
carry = true; | |
tmp -= 10; | |
} | |
v.insert(v.begin(), tmp); | |
} | |
if (carry) v.insert(v.begin(), 1); | |
for (int i = 0; i < v.size(); ++i) cout << v[i]; | |
} |
Python 코드 전문
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
A, B = map(int, input().split()) | |
print(A + B) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 2581번 소수 (C++, Python) (0) | 2022.04.06 |
---|---|
[백준 / BOJ] 1978번 소수 찾기 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 2839번 설탕 배달 (C++, Python) (0) | 2022.04.05 |
[백준 / BOJ] 10250번 ACM 호텔 (C++, Python) (0) | 2022.02.03 |
[백준 / BOJ] 2869번 달팽이는 올라가고 싶다 (C++, Python) (0) | 2022.02.01 |
@Reo :: 코드 아카이브
자기계발 블로그