728x90
큰 수의 덧셈 문제입니다.
수를 입력받아 첫글자부터 차례대로 계산을 합니다.
올림이 생길경우 다음 수에 붙여줍니다.
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int carry = 0;
int num;
string x, y;
string result = "";
string sum()
{
for (int i = 0; i < x.length(); ++i) {
num = (x[i] - '0' + y[i] - '0' + carry) % 10;
result += to_string(num);
carry = (x[i] - '0' + y[i] - '0' + carry) / 10;
}
if (carry != 0) {
result += to_string(carry);
}
return result;
}
int main(int argc, char* argv[])
{
cin >> x >> y;
reverse(x.begin(), x.end());
reverse(y.begin(), y.end());
while (x.length() < y.length()) {
x += '0';
}
while (x.length() > y.length()) {
y += '0';
}
sum();
reverse(result.begin(), result.end());
cout << result;
return 0;
}
'알고리즘' 카테고리의 다른 글
[C++] 백준 10988번 팰린드롬인지 확인하기 (0) | 2019.09.12 |
---|---|
[C++] 백준 15353번 큰 수 A+B (2) (0) | 2019.09.12 |
[C++] 백준 15740번 A+B - 9 (0) | 2019.09.12 |
[C++] 백준 15666번 N과 M (12) (0) | 2019.09.11 |
[C++] 백준 15665번 N과 M (11) (0) | 2019.09.11 |