Leetcode640. Solve the Equation

Description

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”


Solution

因为这道题只涉及+/-,所以Equation的解可以用 x = - (constant / coefficient) 来计算。所以我们只需要区分出coefficient和constant就可以了。

这里可以利用数字后面的char是x还是+/-/=来区别:

  • 如果是x,那就意味着这个数是系数
  • 如果是+/-/=, 那就意味着这个数是常数

Code

//C++
//Time: O(n)
//Space: O(1)
    string solveEquation(string equation) {
        int coef = 0, cons = 0;
        
        int hs = 1; //sign for lhs or rhs
        int sign = 1;   //sign for + or -
        
        char prev = 0;  //previous char
        int num = 0;    //the last number for each i
        
        for(int i = 0; i < equation.size(); ++i){
            //if current char is digit, store it in num
            if(isdigit(equation[i]))
                num = isdigit(prev) ? num * 10 + (equation[i] - '0') : equation[i] - '0';
            
            //if the current char is x, then num is coef
            if(equation[i] == 'x')
                coef += isdigit(prev) ? sign * hs * num : sign * hs * 1;
            
            //is the current char is +/-/=, num is constant
            if(equation[i] == '+' || equation[i] == '-' || equation[i] == '='){
                if(isdigit(prev)){
                    cons += sign * hs * num;
                }
                if(equation[i] == '-' ){
                    sign = -1;
                }
                if(equation[i] == '+' || equation[i] == '='){
                    sign = 1;
                }
            }
            
            prev = equation[i];
            
            //switch side
            if(equation[i] == '='){
                hs = -1;
            }
        }//for
        
        //if the last char is digit, it's constant
        if(isdigit(prev)){
            cons -= sign * num;
        }
        
        //if coef is 0, whether the equation has Infinite solutions
        //or no solution depends on cons
        //if coef is not 0, it always has one solution
        if(coef == 0){
            return cons == 0 ? "Infinite solutions" : "No solution";
        }
        else{
            string res = "x=";
            int ans = (double) cons / coef * (-1);
            res += to_string(ans);
            return res;
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_44344072/article/details/87762983