Google Interview Question for Software Engineer / Developers


Country: -
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
3
of 3 vote

7+8*12+2*(9+4)*7+3 = 288

- Anonymous February 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

Recursively evaluate the expression, no need for explicit stack. Didn't have the time to refactor the code though.

import java.util.ArrayList;

public class ExpressionEval {
	int step=0;
	public void printExpressionResult(String text){
		String[] words = text.split(" ");
		System.out.println(eval(words));
	}
	
	public int eval(String[] words){
		ArrayList<Integer> vals = new ArrayList<Integer>();
		String opr = "";
		while(step<words.length){
			if(words[step].equals("+")||words[step].equals("-")||words[step].equals("*")||words[step].equals("/")){
				opr=words[step];
				step++;
			}
			else if(words[step].equals("(")){
				step++;
				vals.add(eval(words));
			}
			else if(words[step].equals(")"))
			{
				step++;
				break;
			}
			else{
				vals.add(Integer.parseInt(words[step]));
				step++;
			}
		}
		if(vals.size()==1)
			return vals.get(0);
		int res=0;
		if(opr.equals("+")){
			res=0;
			for(Integer num:vals)
				res+=num;
		}
		else if(opr.equals("*")){
			res=1;
			for(Integer num:vals)
				res*=num;
		}
		else if(opr.equals("-")){
			res=vals.get(0);
			for(int i=1;i<vals.size();i++)
				res-=vals.get(i);
		}
		else if(opr.equals("/")){
			res=vals.get(0);
			for(int i=1;i<vals.size();i++)
				res/=vals.get(i);
		}
		return res;
	}
	
	public static void main(String[] args){
		ExpressionEval exp = new ExpressionEval();
		exp.printExpressionResult("( + 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3 )" );
	}
}

- Coder.Yao February 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Here is the Stack implementation of Polish Notation Calculator. Logic runs as below
1. Split the given string into a string array
2. Start from the back of the array
3. If you find braces "(" or ")" just ignore
4. If you find an operand, push onto stack
5. If you find an operator, pop two top operands, calculate result and then push back the result to stack.

Implementation goes below

package career.cup.string;

import java.util.Stack;

public class polishNotation {
	
	public static void main(String[] args) {
		System.out.println(polishNotationCalculation("( + + 7 ( * 8 12 ) ( * * 2 ( + 9 4 ) 7 )"));
	}
	
	public static int polishNotationCalculation(String strCalc){
		Stack sk = new Stack<String>();
		String operation = null;
		String operand1 = null;
		String operand2 = null;
		
		String[] opList = strCalc.split(" ");
		
		for(int i = opList.length-1; i>=0;i--){
			String S = opList[i];
			if(S.equals("(") || S.equals(")")) {
				continue;
			} 
			if(S.equals("+") || S.equals("-") 
						|| S.equals("*") || S.equals("/")){
				operation = S;
				if(!sk.isEmpty()){
					operand1 = (String)sk.pop();
					}
				if(!sk.isEmpty()){
					operand2 = (String)sk.pop();
					}
				int interResult = performCalc(operand1,operand2,operation);
				sk.push(String.valueOf(interResult));
				
			}else {
				sk.push(S);
			}
			
		}
		
		String result = (String)sk.pop();
		System.out.println("Result is "+result);
		return Integer.valueOf(result);
	}

	private static int performCalc(String operand1, String operand2,
			String operation) {
		// TODO Auto-generated method stub
		int result =0;
		switch (operation.charAt(0)) {
		case '+':
			result = Integer.valueOf(operand1) + Integer.valueOf(operand2);
			break;
		case '-':	
			result = Integer.valueOf(operand1) - Integer.valueOf(operand2);
			break;
		case '*':	
			result = Integer.valueOf(operand1) * Integer.valueOf(operand2);
			break;
		case '/':	
			result = Integer.valueOf(operand1) / Integer.valueOf(operand2);
			break;
		default:
			break;
		}
		return result;
	}

}

- hm February 12, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

( + 7 ( * 8 12 ) ( * 2 (+ 9 4) 7 ) 3 ) gives 103
not 148.

- rew September 10, 2015 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

simple recursive:

static int calExpression(String word) {
        return calExpression(word.split(" "));
    }

    static int calExpression(String[] words) {
        String currOps = null;
        List<Integer> nums = new ArrayList<Integer>();
        for (; index < words.length; index++) {
            switch (words[index]) {
                case "(":
                    ++index;
                    int res = calExpression(words);
                    nums.add(res);
                    break;
                case ")":
                    return calNums(nums, currOps);
                default:
                    if (isOperator(words[index])) {
                        currOps = words[index];
                    } else {
                        nums.add(Integer.valueOf(words[index]));
                    }
                    break;
            }
        }

        return calNums(nums, currOps);
    }

    static int calNums(List<Integer> nums, String expression) {
        int res = 0;
        if (expression == null)
            expression = "*";
        switch (expression) {
            case "+":
                for (Integer num : nums)
                    res += num;
                break;
            case "-":
                for (Integer num : nums)
                    res -= num;
                break;
            case "/":
                res = nums.get(0);
                for (int index = 1; index < nums.size(); index++)
                    res /= nums.get(index);
                break;
            default:
                res = 1;
                for (Integer num : nums)
                    res *= num;
                break;
        }
        return res;
    }

    static boolean isOperator(String input) {
        switch (input) {
            case "+":
            case "-":
            case "/":
            case "*":
                return true;
            default:
                return false;
        }
    }

- ghs February 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Build a tree: each node contains either an integer or an operator plus links to subtrees

Do the math in post-order search.

It is tedious coding, but relatively straight forward.

- w.y February 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The algorithm is something like this:

You need to use two stacks. one for operator, one for numbers.

When you add two numbers onto the number stack and add an operator, you check if the previous operator (on the stack) is of higher precedence. if it does, then you calculate those numbers first.

I apologize, but I'm not sure what you do when you have parentheses though - it has higher operator precedence so I think you calculate everything in it until you get a close parenthesis?

- Skor February 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Stack;

public class Calculator
{
  private interface Expression
  {
    int evaluate();
  }

  private static abstract class CompositeExpression implements Expression
  {
    private List<Expression> expressions = new LinkedList<>();

    public void addExpression(Expression e)
    {
      expressions.add(e);
    }

    protected List<Expression> getExpressions()
    {
      return expressions;
    }
  }

  private static class Add extends CompositeExpression
  {
    @Override
    public int evaluate()
    {
      int v = 0;
      for (Expression e : getExpressions())
      {
        v += e.evaluate();
      }
      return v;
    }
  }

  private static class Subtract extends CompositeExpression
  {
    @Override
    public int evaluate()
    {
      Iterator<Expression> i = getExpressions().iterator();
      if (!i.hasNext())
      {
        throw new RuntimeException("Invalid subtract expression");
      }
      int v = i.next().evaluate();
      while (i.hasNext())
      {
        v -= i.next().evaluate();
      }
      return v;
    }
  }

  private static class Multiply extends CompositeExpression
  {
    @Override
    public int evaluate()
    {
      Iterator<Expression> i = getExpressions().iterator();
      if (!i.hasNext())
      {
        throw new RuntimeException("Invalid divide expression");
      }
      int v = i.next().evaluate();
      while (i.hasNext())
      {
        v *= i.next().evaluate();
      }
      return v;
    }
  }

  private static class Divide extends CompositeExpression
  {
    @Override
    public int evaluate()
    {
      Iterator<Expression> i = getExpressions().iterator();
      if (!i.hasNext())
      {
        throw new RuntimeException("Invalid divide expression");
      }
      int v = i.next().evaluate();
      while (i.hasNext())
      {
        v /= i.next().evaluate();
      }
      return v;
    }
  }

  private static class Value implements Expression
  {
    private int value;

    public Value(int value)
    {
      this.value = value;
    }

    @Override
    public int evaluate()
    {
      return value;
    }
  }

  private static class ExpressionBuilder
  {
    private Stack<CompositeExpression> stack;
    private Expression expression;
    private StringBuilder number;

    public void build(String text)
    {
      stack = new Stack<>();
      number = new StringBuilder();
      for (char c : text.toCharArray())
      {
        switch (c)
        {
          case '+':
            addExpression(new Add());
            break;
          case '-':
            addExpression(new Subtract());
            break;
          case '*':
            addExpression(new Multiply());
            break;
          case '/':
            addExpression(new Divide());
            break;
          case ' ':
          case '(':
            addValue();
            break;
          case ')':
            endExpression();
            break;
          default:
            number.append(c);
        }
      }
      endExpression();
    }

    private void endExpression()
    {
      addValue();
      if (!stack.isEmpty())
      {
        stack.pop();
      }
    }

    private void addExpression(CompositeExpression e)
    {
      if (stack.isEmpty())
      {
        expression = e;
      }
      else
      {
        stack.peek().addExpression(e);
      }
      stack.push(e);
    }

    private void addValue()
    {
      if (number.length() > 0)
      {
        Value value = new Value(Integer.parseInt(number.toString()));
        if (stack.isEmpty())
        {
          expression = value;
        }
        else
        {
          stack.peek().addExpression(value);
        }
        number.setLength(0);
      }
    }

    public Expression getExpression()
    {
      return expression;
    }
  }

  public static Expression parse(String text)
  {
    ExpressionBuilder builder = new ExpressionBuilder();
    builder.build(text);
    return builder.getExpression();
  }

  public static int calculate(String text)
  {
    Expression expression = parse(text);
    return expression.evaluate();
  }
}

- Anonymous February 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

this is Prefix notation, which can be easily solved using stacks

check this link : en.wikipedia.org/wiki/Polish_notation

- Source February 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Easy to extend with other functions, and to sligthly refactor.

from functools import reduce

def calculate(s):
    tokens = s.split()
    return calculator(tokens, 0, len(tokens)-1)

def calculator(tokens, start, end):
    if tokens[start] == "(":
        start += 1
        end -= 1

    if tokens[start] in ("+", "-", "*"):
        operands = []
        tmp_start = start + 1
        c = 0
        parenthesis_start = tmp_start
        
        while (tmp_start <= end):
            if tokens[tmp_start] == "(":
                if c==0:
                    parenthesis_start = tmp_start
                c+=1
            elif tokens[tmp_start] == ")":
                c-=1
                if c==0:
                    operands.append(calculator(tokens, parenthesis_start, tmp_start))
            elif c == 0:
                operands.append(int(tokens[tmp_start]))
            tmp_start += 1
        if tokens[start] == "+":
            return sum(operands)
        elif tokens[start] == "-":
            return sum([-o for o in operands])
        elif tokens[start] == "*":
            return reduce(lambda x, y: x*y, operands, 1)
    else:
        raise NotImplemented()

if __name__ == "__main__":
    print(calculate("+ 2 4"))
    print(calculate("* 8 ( + 7 12 )"))
    print(calculate("( + 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3 )"))
    print(calculate("( + 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3 ( - 8 ) )"))

- eole February 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

First of all the format of the third string is WRONG

I found this simple recursive solution, the c++ code is quite simple to follow, this algorithm works even if the spaces are missing, let me know of if you have any questions:

#include "stdafx.h"
#include "conio.h"

int StringValue( char * str, int& pos )
{
	if ( !pos )
	{
		printf("%s = ", str );
	}

	int total = 0;

	int operand1, operand2;

	switch ( str[ pos ] )
	{
	case ' ':
		pos++;
		total = StringValue( str , pos );
		break;

	case '+':
		pos++;
		operand1 = StringValue( str , pos );
		operand2 = StringValue( str , pos );
		total = operand1 + operand2;
		break;

	case '-':
		pos++;
		operand1 = StringValue( str , pos );
		operand2 = StringValue( str , pos );
		total = operand1 - operand2;
		break;

	case '*':
		pos++;
		operand1 = StringValue( str , pos );
		operand2 = StringValue( str , pos );
		total = operand1 * operand2;
		break;

	case '/':
		pos++;
		operand1 = StringValue( str , pos );
		operand2 = StringValue( str , pos );
		total = operand1 / operand2;
		break;

	case '(':
		pos++;
		total = StringValue( str , pos );
		while ( ( str[pos] != ')' ) && ( str[pos] ) )
		{
			pos++;
		}
		pos++;
		break;

	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
		total = str[pos] - '0';
		pos++;
		while ( ( str[pos] >= '0' ) && ( str[pos] <= '9' ) )
		{
			total = total*10 + str[pos] - '0';
			pos++;
		}
		break;
	}

	return total;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int pos = 0;

	pos = 0;
	printf("%d \n", StringValue("+ 2 4", pos) );

	pos = 0;
	printf("%d \n", StringValue("* 8 ( + 7 12 )", pos) );

	pos = 0;
	printf("%d \n", StringValue("( + 7 12 )", pos) );

	pos = 0;
	printf("%d \n", StringValue("( * * 2 ( + 9 4 ) 7 )", pos) );

	pos = 0;
	printf("%d \n", StringValue("( + 7 ( * 8 12 ) )", pos) );

	pos = 0;
	printf("%d \n", StringValue("( + + 7 ( * 8 12 ) ( * * 2 ( + 9 4 ) 7 )", pos) );

	getch();

	return 0;
}

- koosha.nejad February 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

My program output:
+ 2 4 = 6
* 8 ( + 7 12 ) = 152
( + 7 12 ) = 19
( * * 2 ( + 9 4 ) 7 ) = 182
( + 7 ( * 8 12 ) ) = 103
( + + 7 ( * 8 12 ) ( * * 2 ( + 9 4 ) 7 ) = 285
(++ 7( * 8 12 )( **2 ( + 9 4 )7 ) = 285

- koosha.nejad February 11, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

String getIntermediateres(String operator, Stack<String> st)
{
				String res="";
				if(temp.equals("+"))
				{
					int op1=Integer.parseInt(st2.pop());
					int op2=Integer.parseInt(st2.pop());
					int op3=op1+op2;
					res=op3+"";
					
				}else if(temp.equals("-"))
				{
					int op1=Integer.parseInt(st2.pop());
					int op2=Integer.parseInt(st2.pop());
					int op3=-op1+op2;
					res=op3+"";
					

				}else if(temp.equals("*"))
				{
					int op1=Integer.parseInt(st2.pop());
					int op2=Integer.parseInt(st2.pop());
					int op3=op2*op1;
					res=op3+"";
					
				}else if(temp.equals("/"))
				{
					int op1=Integer.parseInt(st2.pop());
					int op2=Integer.parseInt(st2.pop());
					int op3=op2/op1;
					res=op3+"";
					
				}

	return res;
}


int getCalculator(String inp)
{
	String[] inp_set=inp.split();
	int res=0;
	if(len==0) 
		return res;

	Stack<String> st1=new Stack<String>();
	Stack<String> st2=new Stack<String>();
	int len=inp_set.length;

	for(String s: inp_set)
	{
		if(s.equals("(") || s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/"))
		{
			st1.add(s);
		}else if(s.equals(")"))
		{
			String temp=st2.pop();
			while(!temp.equals("("))
			{
				st2.add(getIntermediateres(temp,st2));
				temp=st2.pop();
			}

		}else{
			st2.add(s);
		}
	}

	while(!st1.isEmpty())
	{
		String temp=st1.pop();
		st2.add(getIntermediateres(temp,st2));
	}

	return Integer.parseInt(st2.pop());

}

- Mir February 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def turnIntoArray(input):
    returnArray = []
    i = 0
    nextToken = ""
    while i < len(input):
        if input[i] is "(":
            array, j = turnIntoArray(input[i+1:])
            i += j
            returnArray.append(array)
        elif input[i] is ")":
            return (returnArray, i+1)
        elif input[i] is " " and nextToken is not "":
            returnArray.append(nextToken)
            nextToken = ""
        elif input[i] is not " ":
            nextToken += input[i]
        i += 1
    if nextToken is not "":
        returnArray.append(nextToken)
    return (returnArray, i)

def evalList(listToken):
    if not isinstance(listToken, list):
        return int(listToken)

    if isinstance(listToken[0], list):
        return evalList(listToken[0])

    if listToken[0] == "+":
        result = 0
        for item in listToken[1:]:
            result += evalList(item)
        return result
    elif listToken[0] == "-":
        return evalList(listToken[1]) - evalList(listToken[2])
    elif listToken[0] == "*":
        result = 1
        for item in listToken[1:]:
            result *= evalList(item)
        return result
    elif listToken[0] == "/":
        return evalList(listToken[1]) / evalList(listToken[2])
    else:
        print "something bad happened"


def findResult(input):
    array, i = turnIntoArray(input)
    print evalList(array)

findResult("( + 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3 )")

- Adi February 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Iterative version with stack:

#include <stdio.h>

static int compute(char *str)
{
        int op[100], num[100], i, o = 0, val;

        for (i = 0; i < 100; i++)
                num[i] = -1;

        for (i = 0; str[i]; i++) {
                if (str[i] == ' ')
                        continue;
                if (str[i] == '(') {
                        o++;
                        num[o] = -1;
                        continue;
                }
                if (str[i] == '+') {
                        op[o] = 1;
                        continue;
                }
                if (str[i] == '*') {
                        op[o] = 2;
                        continue;
                }
                if (str[i] == ')') {
                        val = num[o];
                        o--;
                        goto add;
                }

                for (val = 0; str[i] && str[i] != ' '; i++) {
                        val *= 10;
                        val += str[i] - '0';
                }

add:
                if (num[o] < 0)
                        num[o] = val;
                else if (op[o] == 1)
                        num[o] += val;
                else if (op[o] == 2)
                        num[o] *= val;
        }
        return num[o];
}

int main(void)
{
        printf("%d\n", compute("( + 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3 )"));
        return 0;
}

- ken February 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string>
using std::string;

int calculate(string expr) {
  int len = int(expr.size());
  int ub = 0;
  
  int op_plus = true;
  int total = 0;
  while (ub < len) {
    int lb = ub;
    ++ub;

    if (expr[lb] == '+' || expr[lb] == ' ') {
      continue;
    }

    if (expr[lb] == '*') {
      op_plus = false;
      total = 1;
      continue;
    }

    int num = 0;
    if ('0' <= expr[lb] && expr[lb] <= '9') {
      while (ub < len && '0' <= expr[ub] && expr[ub] <= '9') {
        ++ub;
      }
      num = std::stoi(expr.substr(lb, ub-lb));
    }
    else if (expr[lb] == '(') {
      int c = 1;
      ++ub;
      while (ub < len && c) {
        if (expr[ub] == '(') {
          ++c;
        }
        else if (expr[ub] == ')') {
          --c;
        }
        ++ub;
      }
      num = calculate(expr.substr(lb+1, ub-lb-2));
    }
    
    if (op_plus) {
      total += num;
    }
    else {
      total *= num;
    }
  }
  return total;
}

int main() {
  string expr[3] = {
    string("+ 2 4"),
    string("* 8 ( + 7 12)"),
    string("( + 7 ( * 8 12 ) ( * 2 (+ 9 4) 7 ) 3 )")
  };

  for (int i = 0; i < 3; ++i) {
    std::cout << expr[i] << " = " << calculate(expr[i]) << std::endl;
  }
}

- plesiv February 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void evaluatePrefixExp(String exp){
        StringBuilder sb = new StringBuilder(exp);
        sb = sb.reverse();
        Stack s = new Stack();
        int op1, op2;
        for(char c : sb.toString().toCharArray()){
            if(Character.isDigit(c))
            {
                s.push(c);
            }
            else
            {
                op1 = Integer.parseInt(s.pop() + "");
                op2 = Integer.parseInt(s.pop() + "");
                switch(c)
                {
                    case '+':
                        s.push(op1 + op2);
                        break;
                    case '-':
                        s.push(op1 - op2);
                        break;
                    case '*':
                        s.push(op1 * op2);
                        break;
                    case '/':
                        s.push(op1 / op2);
                        break;
                    case '%':
                        s.push(op1 % op2);
                        break;
                }
            }
        }
        System.out.println("Result = " + s.pop());
    }

- chetan March 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

You cannot take as char array and iterate because 12 will be considered as 1 and 2 and you will push 1 and 2 into the stack instead of pushing 12 :)

- rayasamharish October 09, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

what a jegous problem

- wtf March 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct stack {int a[1024]; int n;};

#define push(s, v) ((s)->a[(s)->n ++] = (v))
#define pop(s)     ((s)->a[-- (s)->n])

int main(int argc, char **argv)
{
  struct stack s = {.n = 0};

  for (int i = argc - 1; i; i --)
    switch(*argv[i])
      {
      case '-': push(&s, pop(&s) - pop(&s)); break;
      case '+': push(&s, pop(&s) + pop(&s)); break;
      case '*': push(&s, pop(&s) * pop(&s)); break;
      case '/': push(&s, pop(&s) / pop(&s)); break;
      case '(': case ')': break;
      default: push(&s, strtoul(argv[i], NULL, 0)); break;
      }
  printf("%d\n", pop(&s));
}

- Wolf March 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

$ ./eval '(' + + 7 '(' '*' 8 12 ')' '(' '*' '*' 2 '(' + 9 4 ')' 7
285

- Wolf March 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Solved by basic maths pulled data in stack S
//f(s) = f(operator, s1 , s2)
//s1 and s2 are numbers substack obtained by moving recursively within brackets or after //operators.
//it will work for any length of string as only ListList as been used.
//tested already for many test cases. if still issue, leave a comment.


static boolean ifoperator(String S)
{
boolean b ;
switch (S)
{
case "*":
case "+" :
case "/" :
case "-" :
b = true ; break ;
default:
b = false; break ;
}

return b;
}

static int stack(LinkedList<String> S)
{

//+ ( + 2 3 ) 7
if(ifoperator(S.getFirst()))
{ //System.out.println(S.getFirst());
String op = S.getFirst();
S.removeFirst();
int a = getnum(S);
int b = getnum(S);
return sum(op, a,b);
}
else if (S.getFirst().charAt(0) == '(')
{
S.removeFirst();
int a = stack(S);
return a;

}
else
{

int a = getnum(S);
return a;

}

}

static int getnum(LinkedList<String> S)
{
if(S.isEmpty())
return 0;
if(S.getFirst().charAt(0) == '(' || S.getFirst().charAt(0) == ')')
{
S.removeFirst();
int a = stack(S);
return a;
}
else if(ifoperator(S.getFirst()))
{int a = stack(S);return a;}
else
{
int a = Integer.parseInt(S.getFirst());
S.removeFirst();
return a;
}

}


static int sum(String op, int a , int b)
{ int val = 0 ;


switch (op)
{
case "+":
val = a +b ;
break;
case "-":
val = a - b ;
break;
case "*":
val = a * b ;
break;
case "/":
val = a / b ;
break;
}

//System.out.println("All OKay => " + val);
return val;
}


public static void main (String[] args) throws java.lang.Exception
{
LinkedList<String> exp = new LinkedList<String>();
//String s1 = "+ ( * 5 6 ) ( 7 )";
//String s1 = "* 8 ( + 7 12 )";
//String s1 = "( + + ( + 7 ( * 8 12 ) ) ( * 2 ( * ( + 9 4 ) 7 ) ) 3 )";
String s1 = "( + + + 7 ( * 8 12 ) ( * * 2 ( + 9 4 ) 7 ) 3 )" ;
//7 //96 *2 13 * 7
String temp[] = s1.split(" ");
//System.out.println(temp.length);
//( + ( + 2 3 ) ( * 5 6 ) )
for(int i =0; i<temp.length; i++)
exp.addLast(temp[i]);



System.out.println(stack(exp));

}

- ABHI.AKS.SINGH June 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

is the question correct
( + 7 ( * 8 12 ) ( * 2 (+ 9 4) 7 ) 3 )
should be
( ++7 ( * 8 12 ) ( ** 2 (+ 9 4) 7 ) 3 )
right???

- rewati.raman September 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def calculate(a):
    a = a.split()
    i = 0
    while i<len(a):
        if a[i]=='+' or a[i]=='-' or a[i]=='*' or a[i]=='/':
            a[i],a[i+1] = a[i+1], a[i]
            i += 2
        else:
            i += 1
    a =''.join(a)
    a = eval(a)
    return a

- hnvasa November 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

assertEquals(calculator.calculateNAryPrefixNotation("+ 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3"), 288);

    private int calculateNAryPrefixNotation(String expr) {
        String[] parts = expr.split(" ");
        return calculateNAryPrefixNotation(parts, new int[]{parts.length - 1});
    }

    private int calculateNAryPrefixNotation(String[] parts, int[] pointer) {
        int result = 0;
        Stack<Integer> digits = new Stack<>();
        while (pointer[0] >= 0) {
            String part = parts[pointer[0]--];
            if (part.equals(")")) digits.push(calculateNAryPrefixNotation(parts, pointer));
            else if (part.equals("(")) return result;
            else if (part.equals("+") || part.equals("-") || part.equals("*")) {
                result = digits.pop();
                do {
                    int val = digits.pop();
                    if (part.equals("+")) result += val;
                    else if (part.equals("*")) result *= val;
                    else if (part.equals("-")) result -= val;
                } while (!digits.isEmpty());
            } else digits.push(Integer.parseInt(part));
        }
        return result;
    }

- spodgurskiy April 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int calculator(String s) {
if (null==s || 0==s.length()) return 0;
System.out.println(s);
String expr[] = s.split(" ");
String operator = "+-*/";
String parenthese= "()[]";

Stack<Integer> stack = new Stack<Integer>();
int len = expr.length;
int a,b;
for (int i=len-1;i>=0;i--) {
String t = expr[i];
if (!operator.contains(t)) {
if (!parenthese.contains(t)) { // it is number
stack.push(Integer.valueOf(t));
}
} else {
while (stack.size()>1) { // stack.size() >2 , we must make sure it be one
a = stack.pop();
b = stack.pop();
switch (t) {
case "+":
stack.push(a + b);
break;
case "-":
stack.push(b - a); // substraction is second data minus first data
break;
case "*":
stack.push(a * b);
break;
case "/":
stack.push(b / a); // divid is second be divided by first one
break;
}
}
}
}
return stack.pop();

}

public static int parseString(String s) {
if (null==s || 0==s.length()) return 0;
String expr[] = s.split(" ");
Stack<String> stack = new Stack<String>();
for (String ss:expr) {
if (!ss.equals(")")) {
stack.add(ss);
} else {

String buf = "";
while (!stack.peek().equals("(")) {
buf = stack.pop()+" "+buf;

}
if (!buf.equals("")) {
stack.pop(); // remove "("
int curr = calculator(buf);
System.out.println(curr);
stack.push(String.valueOf(curr));
}
}
}
return Integer.valueOf(stack.pop());
}

- John Zhang August 26, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

what i did is: a recursion that is called on each expression between parenthesis. the result is put into queue. in the end, i will have a queue with operation and numbers.

package helloworld;

import java.util.LinkedList;
import java.util.Queue;

public class CalcExp {
	String exp;

	public CalcExp(String exp) {
		this.exp = exp;
	}

	public Integer calc() throws Exception{
		Queue<String> q = new LinkedList<String>();
		int i =0;
		for(String str : exp.split(" ")){
			i += str.length()+1; // plus one for the space
			if(str.equals("(")){
				exp = exp.substring(i);
				i=0;
				q.add(calc().toString());
				if(exp.equals("")){
					break;
				}
				
				continue;
			}
			if(str.equals("*") ||str.equals("/") ||str.equals("+") ||str.equals("-") ){
				q.add(str);
				continue;
			}
			if(str.equals(" ")){
				continue;
			}
			if(str.equals(")")){
				exp = exp.substring(i-1);
				i=0;
				return calcStack(q);
			}
			// if we reached here then we have a digit.
			q.add(str);
		}
		return calcStack(q);
	}

	private int calculate(String op, int op1, int op2) throws Exception {
		if (op.equals("*")) {
			return op1 * op2;
		}
		if (op.equals("/")) {
			return op1 / op2;
		}
		if (op.equals("-")) {
			return op1 - op2;
		}
		if (op.equals("+")) {
			return op1 + op2;
		}
		throw new Exception("Operation " + op + " is not familiar");

	}

	private int calcStack(Queue<String> q) throws Exception {
		int op1;
		int op2;
		int result = 0;
		String currOp = null;
		while (! q.isEmpty()) {
			String str = q.poll();
			if (str.equals("*") || str.equals("/") || str.equals("+") || str.equals("-")) {
				currOp = new String(str);
				op1 = Integer.parseInt(q.poll());
				op2 = Integer.parseInt(q.poll());
				result = calculate(currOp, op1, op2);
			}else{
				op2 = Integer.parseInt(str);
				result = calculate(currOp, result, op2);
			}
		}
		return result;
	}

	public static void main(String[] args) throws Exception {
		String exp =  "* 8 ( + 7 5 )";
		System.out.println(exp + " equals: " + new CalcExp(exp).calc());
		exp = "+ 7 5";
		System.out.println(exp + " equals: " + new CalcExp(exp).calc());
	}
}

- littlefinger September 03, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Shunting-yard_algorithm

- Akshay February 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Shunting yard algorithm is for converting from regular notation to reverse polish notation.

- SK February 02, 2015 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More