LeetCode #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"

class Solution {
public:
    string solveEquation(string equation) {
        string left,right;
        istringstream iss(equation);
        getline(iss,left,'=');
        getline(iss,right,'=');
        int left_x=0, left_num=0, right_x=0, right_num=0;
        helper(left,left_x,left_num);
        helper(right,right_x,right_num);
        int x=left_x-right_x;
        int num=right_num-left_num;
        if(x==0&&num!=0) return "No solution";
        else if(x==0&&num==0) return "Infinite solutions";
        else return "x="+to_string(num/x);
    }
    
    void helper(string equation, int& x, int& num) //根据加减号分割表达式,计算表达式中x的系数和常数
    {
        int i=0;
        int j=0;
        while(j<equation.size())
        {
            while(j!=equation.size()-1&&equation[j+1]!='+'&&equation[j+1]!='-') j++;
            string s=equation.substr(i,j-i+1);
            int sign=1;
            if(s[0]=='-') sign=-1;
            if(s[0]=='+'||s[0]=='-') s=s.substr(1);
            if(s=="x") x+=sign; //当s=="x"时,不存在系数,所以要单独判断
            else if(s.back()=='x')  x+=sign*atoi(s.substr(0,s.size()-1).c_str());
            else num+=sign*atoi(s.c_str());
            j++;
            i=j;
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值