Java beat 100%, evaluate sum and x count


  • 0

    For the two side of the equation we evaluate the count of x and the sum of the rest numbers.

        private static int[] eval(String s) {
            int sum = 0, count = 0, sign = 1;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '+' || c == '-') {
                    sign = c == '+' ? 1 : -1;
                } else if (c == 'x') {
                    count += sign;
                } else {
                    int num = 0;
                    while (i < s.length() && Character.isDigit(s.charAt(i))) {
                        num = num * 10 + s.charAt(i++) - '0';
                    }
                    if (i < s.length() && s.charAt(i) == 'x') count += num * sign;
                    else {
                        sum += num * sign;
                        i--;
                    }
                }
            }
            return new int[]{sum, count};
        }
        public static String solveEquation(String equation) {
            String[] e = equation.split("=");
            int[] l = eval(e[0]), r = eval(e[1]);
            if (l[1] == r[1]) {
                if (l[0] == r[0]) return "Infinite solutions";
                else return "No solution";
            } else {
                return "x="+((r[0]-l[0])/(l[1]-r[1]));
            }
        }
    

Log in to reply
 

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