Skip to content

Instantly share code, notes, and snippets.

@gladilindv
Last active March 22, 2018 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladilindv/840f6b14065ba46f20ab674012c4b594 to your computer and use it in GitHub Desktop.
Save gladilindv/840f6b14065ba46f20ab674012c4b594 to your computer and use it in GitHub Desktop.
// Example program
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
// ----------------------------------------------------------
// ряд вспомогательных функций
static inline void removeChar(string& s, char c){
auto it = s.begin();
while(*it)
it = std::remove(it, s.end(), c);
}
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
// ----------------------------------------------------------
/*
* сложение без учета отрицательных чисел
* и без проверок на валидность числа
*/
int main()
{
string s1 = " 87'276'218'446'744'336'854'775'808";
string s2 = "187'276'218'446'744'336'854'775'808";
{
// ряд подготовительных операций
removeChar(s1, '\'');
removeChar(s2, '\'');
cout << s1 << "\n" << s2 << endl;
trim(s1);
trim(s2);
}
// разворачиваем строки (исключительно ради для удобства)
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
// находим минимум и максимум длин строк
string* strmax = nullptr;
unsigned min = s1.size();
unsigned max = min;
if(min > s2.size()){
min = s2.size();
strmax = &s1;
} else {
max = s2.size();
strmax = &s2;
}
// результат сложения
string sum = "";
// признак переполнения регистра
bool o = false;
for(unsigned i = 0; i < min; i++){
// получаем численное значение символа-цифры
short l = s1.at(i) - '0';
short r = s2.at(i) - '0';
// численное значение i-го регистра
short s = l + r;
if(o) s++;
// учет переполнения регистра
o = (s / 10) > 0;
// преобразование к символу
sum += string(1, (s % 10) + '0');
}
// дополняем результат символами бОльшей строки
// с учетом переполнения регистра
for(unsigned i = min; i < max; i++){
if(o){
short s = strmax->at(i) - '0' + 1;
o = (s / 10) > 0;
sum += string(1, (s % 10) + '0');
}
else
sum += strmax->at(i);
}
// разворачиваем
reverse(sum.begin(), sum.end());
// результат сложения
cout << sum << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment