Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdint>
- #include <iostream>
- #include <optional>
- #include <limits>
- using namespace std;
- template <typename T>
- std::optional<T> SafeAdd(T a, T b) {
- if ((a < 0 && b < 0 && a < std::numeric_limits<T>::min() - b) || (a > 0 && b > 0 && a > std::numeric_limits<T>::max() - b)) {
- return std::nullopt;
- } else {
- return a + b;
- }
- }
- int main() {
- int64_t a;
- int64_t b;
- cin >> a >> b;
- if (SafeAdd(a,b)) {
- std::cout << a + b << std::endl;
- } else {
- std::cout << "Overflow!"sv << std::endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment