Advertisement
kutuzzzov

Урок 3 выполнение оптимизаций

Jul 12th, 2023
1,411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. #include <cstdint>
  2. #include <iostream>
  3. #include <optional>
  4. #include <limits>
  5.  
  6. using namespace std;
  7.  
  8. template <typename T>
  9. optional<T> SafeAdd(T a, T b) {
  10.     if (a > 0 && b > 0) {
  11.         if (a > std::numeric_limits<T>::max() - b) {
  12.             return nullopt;
  13.         }
  14.     }
  15.     if (a < 0 && b < 0) {
  16.         if (a < std::numeric_limits<T>::min() - b) {
  17.             return nullopt;
  18.         }
  19.     }
  20.     return a + b;
  21. }
  22.  
  23. int main() {
  24.     int64_t a;
  25.     int64_t b;
  26.     cin >> a >> b;
  27.     auto res = SafeAdd(a, b);
  28.     if (res.has_value()) {
  29.         cout << res.value() << endl;
  30.     }
  31.     else {
  32.         cout << "Overflow!" << endl;
  33.     }
  34.    
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement