Easy TO understand by using queue to store number


  • 0
    J

    Using Queue to store the number

     public String solveEquation(String equation) {
            int i = 0;
            while (i < equation.length()){
                char c = equation.charAt(i);
                if (c == '='){
                    break;
                }
                i++;
            }
            String left = equation.substring(0, i);
            String right = equation.substring(i + 1);
            int[] num1 = help(left);
            int[] num2 = help(right);
            if (num1[0] == num2[0] && num1[1] == num2[1]){
                return "Infinite solutions";
            } else if (num1[1] == num2[1]){ 
                return "No solution";
            } else {
                int temp = (num2[0] - num1[0]) / (num1[1] - num2[1]);
                System.out.print(temp);
                return "x=" + temp;
            }
            
        }
        public int[] help(String left){
             Queue<Integer> Q = new LinkedList<Integer>();
            int num1 = 0;
            int num2 = 0;
            boolean positive = true;
            for (int i = 0; i < left.length(); i++){
                char c = left.charAt(i);
                if (c == '+' || c== '-'){
                    int temp = 0;
                    while (!Q.isEmpty()){
                        temp = temp * 10 + Q.poll();
                    }
                    if (positive){
                        num1 += temp;
                    }else{
                        num1 -=temp;
                    }
                    if (c == '+'){
                        positive = true;
                    }else{
                        positive = false;
                    } 
                } else if (c == 'x'){
                    int temp = 0;
                    if (Q.isEmpty()){
                       temp = 1;
                    }else {
                       while (!Q.isEmpty()){
                          temp = temp * 10 + Q.poll();
                       }
                    }
                    if (positive){
                        num2 += temp;
                    }else{
                        num2 -= temp;
                    }
                } else {
                    Q.offer(c -'0');
                }
            }
            int temp = 0;
            while (!Q.isEmpty()){
                temp = temp * 10 + Q.poll();
            }
            if (positive){
                num1 += temp;
            }else{
                num1 -= temp;
            }
            return new int[]{num1, num2};
        }
    

Log in to reply
 

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