当前位置:网站首页>640. 求解方程

640. 求解方程

2022-08-10 17:09:00 anieoo

原题链接:640. 求解方程

 

solution:

        

class Solution {
public:
    pair<int, int> work(string str) {
        if(str[0] != '+' && str[0] != '-') str = '+' + str;
        int a = 0, b = 0;
        for(int i = 0;i < str.size();i++) {
            int j = i + 1;
            while(j < str.size() && isdigit(str[j])) j++;
            int c = 1;
            if(i + 1 <= j - 1) c = stoi(str.substr(i + 1, j - i - 1));
            if(str[i] == '-') c = -c;
            if(j < str.size() && str[j] == 'x') {
                a += c;
                i = j;
            } else {
                b += c;
                i = j - 1;
            }
        }
        return {a, b};
    }
    string solveEquation(string equation) {
        int k = equation.find('=');
        auto left = work(equation.substr(0, k)), right = work(equation.substr(k + 1));
        int a = left.first - right.first, b = right.second - left.second;
        if(a == 0) {
            if(b == 0) return "Infinite solutions";
            return "No solution";
        } else {
             return "x=" + to_string(b / a);
        }
    }
};
原网站

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