[Leetcode] 640. Solve the Equation 解题报告

本文介绍了一种解析一元方程的方法,通过分析方程两边的x系数和常数项来求解x的值。提供了具体的算法实现及示例,包括无限解、唯一解和无解的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

 

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

If there is no solution for the equation, return "No solution".

If there are infinite solutions for the equation, return "Infinite solutions".

If there is exactly one solution for the equation, we ensure that the value of x is an integer.

Example 1:

Input: "x+5-3+x=6+x-2"
Output: "x=2"

 

Example 2:

Input: "x=x"
Output: "Infinite solutions"

 

Example 3:

Input: "2x=x"
Output: "x=0"

 

Example 4:

Input: "2x+3x-6x=x+2"
Output: "x=-1"

 

Example 5:

Input: "x=x+2"
Output: "No solution"

思路

我们以等号为界,将方程分为左右两部分,并且分别计算出x的系数以及常数。最后合并同类项,并根据最终的系数和常数返回结果:如果系数为0,若常数也为0则有无穷多解,否则就无解。如果系数不为0,则返回常数除以系数即可。

实现中最麻烦的当属处理"+x", "-x", "+0x", "-0x"以及"x..."等情况。具体可见下面的代码中如何实现。

代码

 

class Solution {
public:
    string solveEquation(string equation) {
        int index = equation.find_first_of('=');
        int left_coe = 0, left_con = 0;
        getValues(equation.substr(0, index), left_coe, left_con);
        int right_coe = 0, right_con = 0;
        getValues(equation.substr(index + 1), right_coe, right_con);
        int coefficient = left_coe - right_coe;
        int constant = right_con - left_con;
        if (coefficient == 0) {
            return constant == 0 ? "Infinite solutions" : "No solution";
        }
        else {
            return "x=" + to_string(constant / coefficient);
        }
    }
private:
    void getValues(string s, int &coefficient, int &constant) {
        int value = 0, sign = 1;
        for (int i = 0; i < s.length(); ++i) {
            if (isdigit(s[i])) {
                value = 10 * value + s[i] -'0';
            }
            else if (s[i] == '+') {
                constant += value * sign;
                value = 0, sign = 1;
            }
            else if (s[i] == '-') {
                constant += value * sign;
                value = 0, sign = -1;
            }
            else if (s[i] == 'x') {
                if (i > 0 && (s[i - 1] == '+' || s[i - 1] == '-')) {
                    value = 1;      // "+x" or "-x"
                }
                if (i == 0) {       // "x" is the leading
                    value = 1;
                }
                coefficient += value * sign;
                value = 0, sign = 1;
            }
        }
        if (s.back() != 'x') {
            constant += value * sign;
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值