Sunday, February 24, 2019

640. Solve the Equation

640Solve 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"
--------------------
解一元一次方程。难点在处理string parsing上。计算左右2边常数项和变量各自的差,sign表示等号左右
class Solution {
    public String solveEquation(String equation) {
        int i = 0, start = 0, cof = 0, cos = 0, sign = 1;
        
        for (; i < equation.length(); i++) {
            if (equation.charAt(i) == '+' || equation.charAt(i) == '-') {
                if (i > start) cos += sign * Integer.parseInt(equation.substring(start,i));
                start = i;
            }else if (equation.charAt(i) == 'x') {
                if (i == start || equation.charAt(i - 1) == '+') {
                    cof += sign;
                }else if (equation.charAt(i - 1) == '-') {
                    cof -= sign;
                }else {
                    cof += sign * Integer.parseInt(equation.substring(start,i));
                }
                
                start = i + 1;
            }else if (equation.charAt(i) == '=') {
                if (i > start) cos += sign * Integer.parseInt(equation.substring(start,i));
                sign = -1;
                start = i + 1;
            }
        }
        
        if (start < equation.length()) cos += sign * Integer.parseInt(equation.substring(start));
        if (cof == 0 && cos == 0) return "Infinite solutions";
        if (cof == 0) return "No solution";
        return "x=" + Integer.toString(- cos / cof);
    }
}

No comments:

Post a Comment