Given a class named Stream which represents a math statement, there are only two elements in Stream:
1. operand: only integer
2. operator: only "+" and "*"
the stream has three methods:
boolean hasNext(); // return true if the Stream has operand or operator left, false if cursor reaches end
int getNum(); // return the next operand, increase cursor in stream
char getOp(); // return the next operator, increase cursor in stream
You need to write a method:
int getValue();
which compute the correct value of the given Stream. Remember "*" has higher priority than "+". You can only use constant space.
Its guaranteed that the Stream is always well-formatted, which means, there wont be Stream like 1 ++ 2 or 12 * 3 +* 4. You dont't need to worry about parsing, just use the above three methods.
public class Stream { public String[] equation; public int index; public int length; public Stream(String eq) { this.equation = eq.split(" "); this.index = 0; this.length = equation.length; } public int getNum() { if (index < length) { return Integer.valueOf(equation[index++]); } return -9999999; } public String getOP() { if (index < length) { return equation[index++]; } return null; } public boolean hasNext() { return index < length; } public int getValue() { this.index = 0; int value = 0; int num = getNum(); while (hasNext()) { String op = getOP(); if (op.equals("+")) { value = value + num; num = getNum(); } else { // op == "*" num = num * getNum(); } } value = value + num; return value; } public static void main(String[] args) { Stream stream = new Stream("4 * 5 * 2 + 3"); System.out.print("value = " + stream.getValue()); } }
damn, don't know how to write this in Java
回覆刪除I have written this in data structure homework in undergrad
回覆刪除作者已經移除這則留言。
回覆刪除