Skip to content

Instantly share code, notes, and snippets.

@msnazarow
Created November 18, 2021 17:40
Show Gist options
  • Save msnazarow/8b5fe6d553ff52208f95802a167aea5e to your computer and use it in GitHub Desktop.
Save msnazarow/8b5fe6d553ff52208f95802a167aea5e to your computer and use it in GitHub Desktop.
BigInt
#include <iostream>
#include <vector>
#include <iomanip>
#define lenBigInt 9
#define divBigInt 1000000000
// Возвращет вектор в обратном порядке, 12 345 678 987 654 123 -> 987654123 12345678
std::vector<unsigned int> parseBigIntReverced(std::string str) {
int i = str.size();
std::vector<unsigned int> vec;
while (i >= 0) {
int offset = std::min(i, lenBigInt);
vec.push_back(std::atoi(str.substr(i - offset, offset).c_str()));
i -= lenBigInt;
}
return vec;
}
std::vector<unsigned int> sumBigInt(std::vector<unsigned int> numbers1, std::vector<unsigned int> numbers2) {
size_t maxOfNumbers = std::max(numbers1.size(), numbers2.size());
std::vector<unsigned int> vec(maxOfNumbers + 1, 0);
for (int i = 0; i < maxOfNumbers; i++) {
unsigned long x, y;
if (i > numbers1.size() - 1) {
x = 0;
} else {
x = numbers1[i];
}
if (i > numbers2.size() - 1) {
y = 0;
} else {
y = numbers2[i];
}
unsigned long sum = x + y;
vec[i] += sum % divBigInt;
vec[i + 1] += sum / divBigInt;
}
return vec;
}
void printBigInt(std::vector<unsigned int> vec) {
int i = vec.size() - 1;
while (i >= 0) {
if (vec[i] != 0) {
break;
}
i--;
}
if (i >= 0) {
std::cout << vec[i];
i--;
while (i >= 0) {
std::cout << std::setfill('0') << std::setw(lenBigInt) << vec[i];
i--;
}
} else {
std::cout << 0;
}
std::cout << std::endl;
}
int main(int argc, char **argv) {
std::string str;
std::cout << "Input first number:" << std::endl;
std::cin >> str;
std::vector<unsigned int> numbers1 = parseBigIntReverced(str);
std::cout << "Input second number:" << std::endl;
std::cin >> str;
std::vector<unsigned int> numbers2 = parseBigIntReverced(str);
std::vector<unsigned int> sum = sumBigInt(numbers1, numbers2);
std::cout << "Result a + b =:" << std::endl;
printBigInt(sum);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment