2012年9月5日 星期三

Twitter phone interview (damn I screw up)

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. 

算是四則運算的簡化版。不過我居然沒在interview時寫出來,真是太弱了。之後從頭想了一下花了半小時寫玩並在eclipse上簡單驗證:


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());
    }
}


3 則留言:

  1. damn, don't know how to write this in Java

    回覆刪除
  2. I have written this in data structure homework in undergrad

    回覆刪除
  3. 作者已經移除這則留言。

    回覆刪除