Skip to content

Latest commit

 

History

History

640

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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"

Companies:
Google, Uber

Related Topics:
Math

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/solve-the-equation/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
private:
    int read(string &equation, int pos, bool &isNum, int &num) {
        if (equation[pos] == '=') ++pos;
        int sign = 1, N = equation.size();
        if (equation[pos] == '+' || equation[pos] == '-') {
            if (equation[pos] == '-') sign = -1;
            ++pos;
        }
        if (pos < N && equation[pos] == 'x') {
            num = 1;
        } else {
            num = 0;
            while (pos < N && isdigit(equation[pos])) {
                num = num * 10 + equation[pos++] - '0';
            }
        }
        isNum = true;
        if (pos < N && equation[pos] == 'x') {
            isNum = false;
            ++pos;
        }
        num *= sign;
        return pos;
    }
public:
    string solveEquation(string equation) {
        int i = 0, N = equation.size(), space = equation.find_first_of("=");
        int coef = 0, val = 0;
        while (i < N) {
            bool isNum;
            int num;
            i = read(equation, i, isNum, num);
            int sign = i <= space ? 1 : -1;
            if (isNum) val -= sign * num;
            else coef += sign * num;
        }
        if (coef) return "x=" + to_string(val / coef);
        return val ? "No solution" : "Infinite solutions";
    }
};