shushus

Спринт 14. Выполнение оптимизаций.

May 5th, 2023
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.59 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. std::optional<T> SafeAdd(T a, T b) {
  10.     if ((a < 0 && b < 0 && a < std::numeric_limits<T>::min() - b) || (a > 0 && b > 0 && a > std::numeric_limits<T>::max() - b)) {
  11.         return std::nullopt;
  12.     } else {
  13.         return a + b;
  14.     }
  15. }
  16.  
  17. int main() {
  18.     int64_t a;
  19.     int64_t b;
  20.     cin >> a >> b;
  21.    
  22.     if (SafeAdd(a,b)) {
  23.         std::cout << a + b << std::endl;
  24.        
  25.     } else {
  26.         std::cout << "Overflow!"sv << std::endl;
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment