알고리즘/BOJ

백준 10757번 큰 수 A+B

꾸준함. 2019. 3. 15. 14:45

문제 링크입니다: https://www.acmicpc.net/problem/10757


c++는 Big Integer를 지원하지 않고 A, B의 범위가 크기 때문에 string을 이용하여 풀어야하는 문제입니다.


#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string Add(string &s1, string &s2)
{
string result(max(s1.size(), s2.size()), '0');
bool carry = false;
for (int i = 0; i < result.size(); i++)
{
int temp = carry;
carry = false;
if (i < s1.size())
temp += s1[s1.size() - i - 1] - '0';
if (i < s2.size())
temp += s2[s2.size() - i - 1] - '0';
if (temp >= 10)
{
carry = true;
temp -= 10;
}
result[result.size() - i - 1] = temp + '0';
}
if (carry)
result.insert(result.begin(), '1');
return result;
}
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
string A, B;
cin >> A >> B;
string result = Add(A, B);
cout << result << "\n";
return 0;
}
view raw .cpp hosted with ❤ by GitHub

개발환경:Visual Studio 2017


지적, 조언, 질문 환영입니다! 댓글 남겨주세요~


반응형

'알고리즘 > BOJ' 카테고리의 다른 글

백준 4307번 개미  (2) 2019.03.15
백준 10826번 피보나치 수 4  (0) 2019.03.15
백준 1850번 최대공약수  (0) 2019.03.15
백준 14891번 톱니바퀴  (0) 2019.03.09
백준 14490번 백대열  (0) 2019.03.07