Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.7 kB
1
Indexable
Never
#include <iostream>
#include <vector>

class LargeInteger {
private:
    std::vector<int> digits;

public:
    LargeInteger(const std::vector<int>& num) : digits(num) {}

    // Function to add two LargeInteger objects
    LargeInteger add(const LargeInteger& other) const {
        LargeInteger result({0}); // Initialize result with a single digit 0

        int carry = 0;
        int size = std::max(digits.size(), other.digits.size());
        std::vector<int> array1(digits.begin(), digits.end());
        std::vector<int> array2(other.digits.begin(), other.digits.end());
        array1.resize(size, 0);
        array2.resize(size, 0);

        // Iterate through each digit and perform addition
        for (int i = size - 1; i >= 0; --i) {
            int total = array1[i] + array2[i] + carry;
            result.digits.insert(result.digits.begin(), total % 10);
            carry = total / 10;
        }

        // If there is a carry after the last digit, add it to the result
        while (carry > 0) {
            result.digits.insert(result.digits.begin(), carry % 10);
            carry /= 10;
        }

        return result;
    }

    // Function to display the LargeInteger
    void display() const {
        for (int digit : digits) {
            std::cout << digit;
        }
        std::cout << std::endl;
    }
};

int main() {
    // Example usage:
    LargeInteger num1({1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
    LargeInteger num2({9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0});

    LargeInteger sum_result = num1.add(num2);

    // Print the result
    std::cout << "Sum: ";
    sum_result.display();

    return 0;
}
Leave a Comment