LeetCode 640. Solve the Equation C++

640. Solve the Equation

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"

Approach

  1. 这道题题目大意很明显就是解方程式,难点主要是该怎么提取有用的字符串,然后进行处理,对这个问题我习惯性分类讨论,就是到哪个字符应该有什么样的操作,这里有四个关键字符,就是+ - x =,不难发现这四个字符是有效数字的结尾,所以我们可以直接进行判断运算即可,看代码会更加容易理解。

Code

class Solution {
public:
    void helper(bool &flag,bool &turn,string &str,int &x,int &con) {
        if (turn) {
            if (str[0] == '-') str = str.substr(1);
            else str = '-' + str;
        }
        if (flag) x += stoi(str);
        else con += stoi(str);
        str.clear();
        flag = false;
    }
    string solveEquation(string equation) {
        int x = 0, con = 0, len = equation.size();
        bool turn = false,flag=false;
        string str = "";
        for (int i = 0; i < len; i++) {
            if (equation[i] == '=') {
                helper(flag, turn, str, x, con);
                turn = true;
            }
            else if (equation[i] == '+') {
                helper(flag, turn, str, x, con);
            }
            else if (equation[i] == '-') {
                if (i!=0&&equation[i - 1] != '=') {
                    helper(flag, turn, str, x, con);
                }
                str="-";
            }
            else if (equation[i] == 'x') {
                if (str == ""||str=="-")str += '1';
                flag = true;
            }
            else
            {
                str += equation[i];
            }
        }
        helper(flag, turn, str, x, con);
        if (x == 0 && con == 0)return "Infinite solutions";
        if (x == 0)return "No solution";
        if (con == 0)return "x=0";
        return "x=" + to_string(-con / x);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值