Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- int ti(char a) { // changes char to int
- int output = a - 48;
- return output;
- }
- char tc(int a) { // changes int to char
- char output = a + 48;
- return output;
- }
- void toMinus(std::string &a) { // 123 -> -1 -2 -3
- for (auto &x : a) {
- x = tc(-ti(x));
- }
- }
- void changeSize(std::string &a, std::string &b) {
- size_t exp_size = std::max(a.size(), b.size()) + 2;
- while (a.size() != exp_size) {
- a = '0' + a;
- }
- while (b.size() != exp_size) {
- b = '0' + b;
- }
- }
- void removeZeros(std::string &a) {
- int i = 0;
- for (; i < a.size(); i++) {
- if (a[i] != '0') {
- break;
- }
- }
- a.erase(0, i);
- if (a.size() == 0) {
- a = "0";
- }
- }
- std::string add(std::string &a, std::string &b) {
- bool neg[2] = {false, false};
- bool out_negative = false;
- if (a[0] == '-') {
- neg[0] = true;
- a.erase(0, 1);
- }
- if (b[0] == '-') {
- neg[1] = true;
- b.erase(0, 1);
- }
- changeSize(a, b);
- if (neg[0] && !(neg[1] && neg[0])) {
- toMinus(a);
- }
- if(neg[1] && !(neg[1] && neg[0])) {
- toMinus(b);
- }
- if (neg[1] && neg[0]) {
- out_negative = true;
- }
- // Dodawanie
- for (int i = a.size() - 1; i > 0; i--) {
- int _a = ti(a[i]);
- int _b = ti(b[i]);
- int out = _a + _b;
- if (out >= 10) {
- a[i - 1] += out / 10;
- } else if (out < 0) {
- if (abs(out) < 10) {
- a[i - 1]--;
- } else {
- a[i - 1] += abs(out) / 10;
- }
- if (i != 1)
- out += 10;
- }
- a[i] = tc(abs(out % 10));
- }
- if (ti(a[0]) == -1) { // Overflow
- out_negative = true;
- a[0] = '0';
- a[1]--;
- for (int i = 2; i < a.size(); i++) {
- if (i == a.size() - 1) {
- a[i] = tc(10 - ti(a[i]));
- } else {
- a[i] = tc(9 - ti(a[i]));
- }
- }
- }
- if (neg[0] && neg[1]) {
- out_negative = true;
- }
- removeZeros(a);
- if (out_negative) {
- a = '-' + a;
- }
- return a;
- }
- int main() {
- std::ios_base::sync_with_stdio(0);
- std::cin.tie(0);
- std::string a;
- std::string b;
- std::cin >> a >> b;
- std::cout << add(a, b);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement