Simple Java solution straight forward parsing


  • 0
    V
    public class Solution {
        public String solveEquation(String equation) {
            if(equation == null || equation.length() == 0) return equation;
            int factor = 1;
            int sign = 1;
            int x = 0;
            int n = 0;
            int s = 0;
    
            for(int i=0; i<equation.length(); i++) {
                if(equation.charAt(i) == '+' || equation.charAt(i) == '-' 
                   || equation.charAt(i) == '=' || i==equation.length()-1) {
                    if(i==equation.length()-1) i++;
                    String elem = equation.substring(s, i);
                    if(!elem.equals("")) {
                        System.out.println("elem : "+elem);
                        if(elem.contains("x")) {
                            String[] num = elem.split("x");
                            if(num.length == 0) {
                                x += sign * factor;
                            } else {
                                x += (Integer.parseInt(num[0]) * sign * factor);
                            }
                        } else {
                            int num = Integer.parseInt(elem);
                            n += num * sign * factor;
                        }    
                    }
                    if(i < equation.length()) {
                        if(equation.charAt(i) == '+') sign = 1;
                        else if(equation.charAt(i) == '-') sign = -1;
                        else {
                            factor = -1;
                            sign = 1;
                        }
                        s = i+1;
                    }
                }
            }
            
            return x==0 && n==0? "Infinite solutions" : x==0? "No solution" : "x="+(n*-1/x);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.