Home > Software engineering >  add/subtract/or multiply as per the given string
add/subtract/or multiply as per the given string

Time:02-26

I was given this problem in an interview, return the output of this String s = "4 8×2" , output = 20, Ex2: String s = "3×7-4", output = 17. This is my approach, but I am not able to get the expected result, please point out the correct way here.

 public static int findResult (String s) {
        int i = 0;
        Stack<String> stack =  new Stack<>();
        while (i < s.length()) {
            if (s.charAt(i) == ' ') {
                stack.push(String.valueOf(s.charAt(i)));
                i  ;
            } else if (s.charAt(i) == '*') {
                stack.push(String.valueOf(s.charAt(i)));
                i  ;
            } else if (s.charAt(i) == '-') {
                stack.push(String.valueOf(s.charAt(i)));
                i  ;
            } else if (Character.isDigit(s.charAt(i))) {
                int num = s.charAt(i) - '0';
                while (i 1 < s.length() && Character.isDigit(s.charAt(i   1))) {
                    num = num * 10   s.charAt(  i) - '0';
                }
                stack.push(String.valueOf(num));
                i  ;
            }
        }
        int current = 0;
        //second while loop
        while (!stack.isEmpty()) {
            int firstNumber = Integer.parseInt(stack.pop());
            if (stack.isEmpty()) return current;
            String sign = stack.pop(""
            //int firstNum = Integer.parseInt(stack.pop());
            if (sign.equals("*")) {
                current = firstNumber * Integer.parseInt(stack.pop());
                stack.push(String.valueOf(current));
            }
            else if (sign.equals("-")) {
                current = firstNumber;
                stack.push(String.valueOf(current));
            } else {
                current = firstNumber   Integer.parseInt(stack.pop());
                stack.push(String.valueOf(current));
            }
        }

        return Integer.parseInt(stack.pop());
    }

CodePudding user response:

This is how I approached this problem. (It is somewhat similar to yours). I'll post the code first, then explain the process below:

import java.util.*;
class Main {
  public static void main(String[] args) {
    System.out.println(findResult("2*57-38*3/5-5-2 3*4/2-2-2"));
  }
   public static double findResult (String s){
     String sub = s;
     ArrayList<Double> nums = new ArrayList<Double>();
     ArrayList<Character> operations = new ArrayList<Character>();
     for(int x = 0; x < s.length(); x  ){
       if(s.charAt(x) == ' ' || s.charAt(x) == '-' || s.charAt(x) == '*' || s.charAt(x) == '/' ){
         operations.add(s.charAt(x));
         int subInd = sub.indexOf(s.charAt(x));
         nums.add(Double.valueOf(sub.substring(0,subInd)));
         sub = sub.substring(subInd   1);
       }
      }
     nums.add(Double.valueOf(sub));
     String[] operationTypes = {"*/"," -"};
     for(int i = 0; i < 2; i  ){
         for(int j = 0; j < operations.size(); j  ){
           if(operationTypes[i].indexOf(operations.get(j)) != -1){
             double val;
             if(operations.get(j) == '*'){
              val = nums.get(j) * nums.get(j 1);
             }
             else if(operations.get(j) == '/'){
              val = nums.get(j) / nums.get(j 1);
             }
             else if(operations.get(j) == ' '){
              val = nums.get(j)   nums.get(j 1);
             }
             else{
              val = nums.get(j) - nums.get(j 1);
             }
             nums.set(j,val);
             nums.remove(j 1);
             operations.remove(j);
             j--;
           }
         }
       }
    return nums.get(0);
  }
}

Yeah...it's a lot:

The first step in this process was to divide the String into two ArrayLists: nums and operations. nums stores the terms and operations stores the..operations (*, /, , -).

Now, we iterate through each "group" of operations, that being multiplication and division, and addition and subtraction.

Starting with mult/div, if we see either a '*' or '/' in our operations, then we compute the product or quotient of the corresponding elements in our nums and edit nums accordingly by modifying the element that matches indexes with the operation and deleting the term following it. Make sure you also remove the operation from nums and decrement the counter variable so the loop does not skip any values.

Finally, we will return the only value left in our nums which will be our answer.

I hope this helped you! Please let me know if you need any further details or clarification :)

  • Related