leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0564.cpp (1368B)


      1 class Solution {
      2     long long generate(long long left, bool isEvenn) const {
      3         long long palindrome = left;
      4         if (!isEvenn) left /= 10;
      5         while (left > 0) {
      6             palindrome = palindrome * 10 + left % 10;
      7             left /= 10;
      8         }
      9         return palindrome;
     10     }
     11 
     12   public:
     13     string nearestPalindromic(const string &s) const {
     14         if (s == "999999999999999999") return "1000000000000000001";
     15 
     16         const long long number = stoll(s);
     17         if (number <= 10) return to_string(number - 1);
     18         if (number == 11) return "9";
     19 
     20         const int n = size(s);
     21         const long long left = stoll(s.substr(0, (n + 1) / 2));
     22 
     23         long long vec[5] = {generate(left - 1, n % 2 == 0), generate(left, n % 2 == 0),
     24                             (long long)pow(10, n - 1) - 1, (long long)pow(10, n) + 1,
     25                             left < 999999999 ? generate(left + 1, n % 2 == 0)
     26                                              : stoll("1" + string(n - 1, '0') + "1")};
     27 
     28         long long res = 0, mini = LLONG_MAX;
     29         for (const auto crnt : vec) {
     30             if (crnt == number) continue;
     31 
     32             const auto diff = abs(crnt - number);
     33             if (diff < mini || (diff == mini && crnt < res)) {
     34                 mini = diff;
     35                 res = crnt;
     36             }
     37         }
     38 
     39         return to_string(res);
     40     }
     41 };