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

本文介绍了一种解析一元方程的方法,通过解析字符串形式的数学表达式来获取方程中未知数的系数和常数项,进而求解方程。代码实现了对方程左右两边分别解析并计算未知数系数和常数项的功能。

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));
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值