• 640. Solve the Equation


    class Solution {
    public:
        string solveEquation(string equation) {
            int idx = equation.find('=');
            
            int x1 = 0, v1 = 0, x2 = 0, v2 = 0, idx1 = 0, idx2 = 0;
            helper(equation.substr(0, idx), idx1, x1, v1);
            helper(equation.substr(idx+1), idx2, x2, v2);
            
            int x = x1 - x2;
            int v = v2 - v1;
            if (x == 0 && v == 0)
                return "Infinite solutions";
            else if (x == 0)
                return "No solution";
            else
                return "x=" + to_string(v / x);
        }
        void helper(const string& s, int& idx, int &x, int &v) {
            int n = s.length();
            if (idx >= n)   return;
            
            int flag = 1;
            if (s[idx] == '+') {
                idx++;
            }
            if (s[idx] == '-') {
                flag = -1;
                idx++;
            }
            if (idx >= n)   return;
            
            if (isdigit(s[idx])) {
                int t = 0;
                while (idx < n && isdigit(s[idx])) {
                    t = t * 10 + s[idx] - '0';
                    idx++;
                }
                if (idx >= n || s[idx] != 'x')
                    v += t * flag;
                else {
                    idx++;
                    x += t * flag;
                }
            }
            else {
                x += 1 * flag;
                idx++;
            }
            
            helper(s, idx, x, v);
        }
    };
  • 相关阅读:
    第十一章关联容器
    第十章泛型算法
    第九章
    第八章
    阅读记录
    java.lang.Class阅读笔记
    java.time包阅读笔记
    CLion运行多个main函数
    c++中lower_bound和upper_bound中的comp参数
    如何写dfs
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/10049568.html
Copyright © 2020-2023  润新知