Sunday, August 23, 2015

Basic Calculator II -- Leetcode

Question:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
Note: Do not use the eval built-in library function.
Answer:
[java]

public class Solution {
    //"3+2*2=7
    public int calculate(String s) {
        if(s==null || s.length() == 0) return 0;

        int len = s.length();
        int res = 0, sign = 1, term = 1, number = 0;
        char op ='+';
        Stack<Integer> stack = new Stack<Integer>();
     
        for(int i=0;i<len;++i){
            char c = s.charAt(i);
            if(Character.isDigit(c)){
                //calculate number for current operand.
               number = c-'0';
               while(i+1<len && Character.isDigit(s.charAt(i+1))){
                   number = number*10 + s.charAt(++i) - '0';
               }
             
               if(op=='+' || op=='-'){
                   term = number;
               }
               else if(op=='*'){
                   term *= number;
               }
               else if(op=='/'){
                   term /= number;
               }
            }
            else if(c=='+'){
                res = res + sign * term;
                op = '+';
                sign = 1;
            }
            else if(c=='-'){
                res = res + sign * term;
                op='-';
                sign = -1;
            }
            else if(c=='*'){
                op = '*';
            }
            else if(c=='/'){
                op = '/';
            }
        }
        //calculate for the final res at last step.
        res = res + sign * term;
        return res;
    }
}


[C++]
class Solution { public: int calculate(string s) { istringstream in(s + "+"); long long total = 0, term, sign = 1, n; in >> term; char op; while (in >> op) { if (op == '+' || op == '-') { total += sign * term; sign = 44 - op; //op == '+' ? 1 : -1 in >> term; } 
else { in >> n; if (op == '*') term *= n; else term /= n; } } return total; } };

No comments:

Post a Comment