leetcode

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

0640.cpp (1021B)


      1 class Solution {
      2     static pair<int, int> count(const string_view &s) {
      3         int x = 0, nums = 0, sign = 1;
      4         for (int i = 0; i < size(s); i++) {
      5             if (s[i] == '+')
      6                 sign = 1;
      7             else if (s[i] == '-')
      8                 sign = -1;
      9             else {
     10                 int num = s[i] == 'x' ? 1 : 0;
     11                 while (isdigit(s[i]))
     12                     num = num * 10 + s[i++] - '0';
     13                 if (s[i] == 'x')
     14                     x += sign * num;
     15                 else
     16                     nums += sign * num, i--;
     17             }
     18         }
     19 
     20         return {x, nums};
     21     }
     22 
     23   public:
     24     string solveEquation(const string &equation) const {
     25         const string_view sv(equation);
     26         const auto it = sv.find('=');
     27 
     28         const auto [lx, ln] = count({begin(sv), it});
     29         const auto [rx, rn] = count(sv.substr(it + 1));
     30 
     31         if (lx == rx) return ln == rn ? "Infinite solutions" : "No solution";
     32         return "x=" + to_string((rn - ln) / (lx - rx));
     33     }
     34 };