작성일 :

문제 링크

15353번 - 큰 수 A+B (2)

설명

이 문제는 일반적인 정수형 타입으로는 담을 수 없는 매우 큰 수 두 개의 합을 직접 구현하는 문제입니다. A, B는 각각 최대 10,000자리의 수이며, 문자열로 입력됩니다.


접근법

  • 입력된 두 수를 문자열로 받아 자릿수 기준으로 뒤에서부터 더해나갑니다.
  • 각 자리마다 두 숫자를 더하고, 10을 넘으면 올림을 처리합니다.
  • 모든 계산이 끝난 후, 가장 앞에 남은 올림수가 있다면 추가해줍니다.
  • 결과는 앞자리부터 차례로 출력해야 하므로 덱(deque)을 활용합니다.

Code

[ C++ ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>

using namespace std;
typedef deque<char> dc;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  string num1, num2; cin >> num1 >> num2;

  if (num1.size() < num2.size()) {
    string tmp = num1;
    num1 = num2;
    num2 = tmp;
  }

  dc ans;
  size_t diff = num1.size() - num2.size();
  for (int i = num2.size() - 1; i >= 0; i--) {
    char num = num2[i] + num1[diff + i] - '0';
    if (num > '9') {
      if (diff + i != 0) {
        num1[i + diff - 1]++;
        num -= 10;
        ans.push_front(num);
      }
      else {
        num -= 10;
        ans.push_front(num);
        ans.push_front('1');
      }
    } else ans.push_front(num);
  }
  for (int i = diff - 1; i >= 0; i--) {
    if (num1[i] > '9') {
      if (i != 0) {
        num1[i - 1]++;
        num1[i] -= 10;
        ans.push_front(num1[i]);
      } else {
        num1[i] -= 10;
        ans.push_front(num1[i]);
        ans.push_front('1');
      }
    } else ans.push_front(num1[i]);
  }

  for (size_t i = 0; i < ans.size(); i++)
    cout << ans[i];
  cout << "\n";

  return 0;
}