当前位置:网站首页>365天挑战LeetCode1000题——Day 053 求解方程 解析 模拟

365天挑战LeetCode1000题——Day 053 求解方程 解析 模拟

2022-08-10 18:29:00 ShowM3TheCode

640. 求解方程

在这里插入图片描述

代码实现(自解)

class Solution {
    
private:
    void parse(string str, int& x, int& co) {
    
        int pstr = 0;
        int n = str.size();
        bool flag = false;
        string tmp = "";
        int val = 0;
        x = 0, co = 0;
        while (pstr != n) {
    
            if (str[pstr] == '-') {
    
                flag = true;
                pstr++;
            }
            else if (str[pstr] == '+') {
    
                pstr++;
            }
            while (str[pstr] >= '0' && str[pstr] <= '9') {
    
                tmp += str[pstr++];
            }
            if (str[pstr] == 'x') {
    
                if (tmp == "") val = 1;
                else val = stoi(tmp);
                if (flag) x -= val;
                else x += val;
                
            }
            else {
    
                if (flag) co -= stoi(tmp);
                else co += stoi(tmp);
                pstr--;
            }

            pstr++;
            flag = false;
            tmp = "";
        }
    }
public:
    string solveEquation(string equation) {
    
        int equal = equation.find('=', 0);
        string left = equation.substr(0, equal);
        string right = equation.substr(equal + 1);
        int x1, co1, x2, co2;
        parse(left, x1, co1);
        parse(right, x2, co2);
        // cout << "x1 : " << x1 << ", co1 : " << co1 << endl;
        // cout << "x2 : " << x2 << ", co2 : " << co2 << endl;
        if (x1 == x2 && co1 == co2) return "Infinite solutions";
        if (x1 == x2 && co1 != co2) return "No solution";
        return "x=" + to_string((co2 - co1) / (x1 - x2));
    }
};
原网站

版权声明
本文为[ShowM3TheCode]所创,转载请带上原文链接,感谢
https://blog.csdn.net/ShowMeTheCod3/article/details/126260894