Advertisement
Swiftkill

Untitled

Oct 1st, 2020 (edited)
971
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. #include <vector>
  5. #include <cctype>
  6.  
  7.     template <class Tc>
  8.     bool next_digit(Tc& c)
  9.     {
  10.         return (std::isdigit(++c)) ? false :  (c = '0', true);
  11.     }
  12.    
  13.     std::string solve(std::string& temp)
  14.     {
  15.         temp.erase(0, std::min(temp.find_first_not_of('0'), temp.size()-1));
  16.         auto len = temp.length();
  17.         auto itc = len/2;
  18.         auto left = itc + len%2 - 1;
  19.         auto right = len - left - 1;//- itc - len%2;
  20.        
  21.         bool carry = true;
  22.         //  std::cout << carry << ":" << left << " - "<< right << '\n';
  23.         if((left == right) /*&& (len > 1)*/)
  24.         {
  25.            if(temp[left-1] <= temp[right+1])
  26.                 carry = next_digit(temp[left]);
  27.  
  28.            if(len >= 3)
  29.                left--, right++;
  30.         }
  31.  
  32.         for(decltype(len) it = 0; it < itc; ++it)
  33.         {
  34.             //std::cout << carry << ":"<< left << " - "<< right << '\n';
  35.             if(carry)
  36.             {
  37.                 if(temp[left] > temp[right])
  38.                 {
  39.                      carry = false;
  40.                      temp[right++] = temp[left--];
  41.                 }
  42.                 else
  43.                 {
  44.                      carry = next_digit(temp[left]);
  45.                      temp[right++] = temp[left--];
  46.                 }
  47.             }
  48.             else
  49.             {
  50.                 if(temp[left] == temp[right]) { carry = false; left--, right++; continue; }
  51.                 temp[right++] = temp[left--];
  52.             }
  53.         }  
  54.  
  55.         if(carry) {
  56.             temp = std::string(len+1, '0');
  57.             temp[0] = '1';
  58.             temp[len] = '1';
  59.         }
  60.         return temp;  
  61.     }
  62.  
  63. int main()
  64. {    
  65.     int n = 0;
  66.    
  67.     std::cin  >> n;
  68.     if (n <= 0)
  69.         return EXIT_SUCCESS;
  70.    
  71.     std::vector<std::string> input(n);
  72.    
  73.     for (auto& str : input)
  74.     {
  75.         std::cin >> str;
  76.     }
  77.    
  78.     for (auto& str : input)
  79.     {
  80.         auto answer = solve(str);
  81.        
  82.         std::cout << answer << std::endl;
  83.     }
  84.  
  85.     return EXIT_SUCCESS;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement