두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
첫째 줄에 A와 B가 주어진다. (0 < A,B < 1010000)
첫째 줄에 A+B를 출력한다.
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string result = "";
string A, B;
cin >> A >> B;
int up = 0;
if (A.size() == B.size()) {
for (int i = B.size() - 1; i >= 0; i--) {
int a = (int)A[i] - (int)'0';
int b = (int)B[i] - (int)'0';
int tmp = a + b + up;
if (tmp >= 10) {
up = 1;
}
else {
up = 0;
}
tmp = tmp % 10;
result += to_string(tmp);
}
if (up == 1) {
result += "1";
}
}
else if (A.size() > B.size()) {
int diff = A.size() - B.size();
for (int i = B.size() - 1; i >= 0; i--) {
int a = (int)A[i + diff] - (int)'0';
int b = (int)B[i] - (int)'0';
int tmp = a + b + up;
if (tmp >= 10) {
up = 1;
}
else {
up = 0;
}
tmp = tmp % 10;
result += to_string(tmp);
}
for (int i = diff - 1; i >= 0; i--) {
int a = (int)A[i] - (int)'0';
int tmp = a + up;
if (tmp >= 10) {
up = 1;
}
else {
up = 0;
}
tmp = tmp % 10;
result += to_string(tmp);
}
}
else if (B.size() > A.size()) {
int diff = B.size() - A.size();
for (int i = A.size() - 1; i >= 0; i--) {
int a = (int)B[i + diff] - (int)'0';
int b = (int)A[i] - (int)'0';
int tmp = a + b + up;
if (tmp >= 10) {
up = 1;
}
else {
up = 0;
}
tmp = tmp % 10;
result += to_string(tmp);
}
for (int i = diff - 1; i >= 0; i--) {
int a = (int)B[i] - (int)'0';
int tmp = a + up;
if (tmp >= 10) {
up = 1;
}
else {
up = 0;
}
tmp = tmp % 10;
result += to_string(tmp);
}
}
for (int i = result.size() - 1; i >= 0; i--) {
cout << result[i];
}
cout << '\n';
return 0;
}
#include <iostream>
#include <algorithm> //reverse
#include <string> // to_string
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string result = "";
string A, B;
cin >> A >> B;
reverse(A.begin(), A.end());
reverse(B.begin(), B.end());
int len;
if (A.length() > B.length()) {
int diff = A.length() - B.length();
for (int i = 0; i < diff; i++) {
B += '0';
}
}
else if (B.length() > A.length()) {
int diff = B.length() - A.length();
for (int i = 0; i < diff; i++) {
A += '0';
}
}
int up = 0;
for (int i = 0; i < A.length(); i++) {
int a = (int)A[i] - (int)'0';
int b = (int)B[i] - (int)'0';
int tmp = a + b + up;
if (tmp >= 10) {
up = 1;
}
else {
up = 0;
}
tmp = tmp % 10;
result += to_string(tmp);
}
if (up == 1) {
result += "1";
}
reverse(result.begin(), result.end());
for (int i = 0; i < result.length(); i++) {
cout << result[i];
}
cout << '\n';
return 0;
}