My omnium-gatherom of scripts and source code.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <cstdint>
5using namespace std;
6
7static string trim(string const& s) {
8 string ret = s;
9 const bool negative = ret.front() == '-';
10 const auto pos = ret.find_first_not_of("-0") - size_t(negative);
11 if (pos != std::string::npos)
12 ret.erase(size_t(negative), pos);
13 return ret;
14}
15
16static std::string subtract([[maybe_unused]] std::string_view str1, [[maybe_unused]] std::string_view str2) {
17 return "";
18}
19
20static std::string add(std::string_view str1, std::string_view str2) { // returns arithmetic addition of str1+str2
21 if (str1.size() == 0)
22 return std::string{str2};
23 else if (str2.size() == 0)
24 return std::string{str1};
25
26 const bool neg1 = str1.front() == '-';
27 const bool neg2 = str2.front() == '-';
28
29 if (neg1)
30 str1.remove_prefix(1);
31 if (neg2)
32 str2.remove_prefix(1);
33
34 if (neg1 && neg2) {
35 return "-" + add(str1, str2);
36 } else if(neg1) {
37 return subtract(str2, str1);
38 } else if(neg2) {
39 return subtract(str1, str2);
40 } else {
41 size_t carry = 0;
42 auto it1 = str1.crbegin();
43 auto it2 = str2.crbegin();
44 const auto end1 = str1.crend();
45 const auto end2 = str2.crend();
46 std::string sum;
47 sum.reserve(std::max(str1.size(), str2.size()));
48 for (; it1 < end1 || it2 < end2; ++it1, ++it2) {
49 uint64_t val1 = it1 < end1 ? uint64_t(*it1) - 48 : 0;
50 uint64_t val2 = it2 < end2 ? uint64_t(*it2) - 48 : 0;
51 uint64_t track_sum = val1 + val2 + carry;
52 carry = track_sum / 10;
53 sum = std::to_string(track_sum % 10) + sum;
54 }
55 if (carry != 0) {
56 sum = std::to_string(carry) + sum;
57 }
58 return trim(sum);
59 }
60}
61
62
63/*
64./build//a.out
65-.0
660.0
67-.0
681
69-100000000000.0
70./build//a.out
71-0
7200
73-0
74100000000000.0
75-00000000000.0
76
77./build//a.out
78 12
79-1.20
80 11
811.20
82 12
83-1.20
84 0
851
86 1
87-100000000000.0
88
89*/
90
91
92auto main() -> int {
93// std::cout << add("1", "1") << std::endl;
94// std::cout << add("-3141526", "-3141526") << std::endl;
95// std::cout << trim("-000000000001.20") << std::endl;
96// std::cout << trim("1000000000001.20") << std::endl;
97// std::cout << trim("-100000000000.0") << std::endl;
98// std::cout << trim("-") << std::endl;
99
100 std::cout << "Hello, world!" << std::endl;
101
102}