[Leetcode]Basic calculator 1 and 2

来源:互联网 发布:oracle数据备份与恢复 编辑:程序博客网 时间:2024/06/14 07:29

[题目]

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces.

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2" 2-1 + 2 " = 3"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.


[思路]

首先...这是十以内单值计算还是10 以上,存在 两位数??! 存在两位数的话还是比较麻烦的....果然不是10以内,那么如何判断数字结束了呢?。。加减号。

Simple iterative solution by identifying characters one by one. One important thing is that the input is valid, which means the parentheses are always paired and in order.Only 5 possible input we need to pay attention:

只是遍历一边string,然后判断每一个character.

  1. digit: it should be one digit from the current number
  2. '+': number is over, we can add the previous number and start a new number
  3. '-': same as above
  4. '(': push the previous result and the sign into the stack, set result to 0, just calculate the new result within the parenthesis.
  5. ')': pop out the top two numbers from stack, first one is the sign before this pair of parenthesis, second is the temporary result before this pair of parenthesis. We add them together.
Finally if there is only one number, from the above solution, we haven't add the number to the result, so we do a check see if the number is zero

[代码]

public int calculate(String s) {    Stack<Integer> stack = new Stack<Integer>();    int result = 0;    int number = 0;    int sign = 1;    for(int i = 0; i < s.length(); i++){        char c = s.charAt(i);        if(Character.isDigit(c)){            number = 10 * number + (int)(c - '0');        }else if(c == '+'){            result += sign * number;            number = 0;            sign = 1;        }else if(c == '-'){            result += sign * number;            number = 0;            sign = -1;        }else if(c == '('){            //we push the result first, then sign;            stack.push(result);            stack.push(sign);            //reset the sign and result for the value in the parenthesis            sign = 1;               result = 0;        }else if(c == ')'){            result += sign * number;              number = 0;            result *= stack.pop();    //stack.pop() is the sign before the parenthesis            result += stack.pop();   //stack.pop() now is the result calculated before the parenthesis        }    }    if(number != 0) result += sign * number;    return result;}

[题目]

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.


[思路]

这道题和 上一个相比的话,()没有了,变成了*/, 共同特点是,需要优先运算. 思路是用两个queue,一个queue 用来装数字,一个queue用来装运算符号。

The idea is to scan from begin to end of the string, handle each case.For case * or /, use two queues to store the number and operater.For case + or -, if the queue is not empty, then we must have previous part with * or / need to be calculated.

[代码]

public class Solution {    public int calculate(String s) {    Queue<Integer> queue = new LinkedList<Integer>();    Queue<Character> cQueue = new LinkedList<Character>();    int temp = 0;    int sign = 1;    int result = 0;    for(int i=0;i<s.length();i++) {        char c = s.charAt(i);        if(Character.isDigit(c)) {            temp = 10 * temp + (int)(c - '0');        }        else if(c == '+') {            if(!queue.isEmpty()) {                temp = calculateQueue(queue, cQueue, temp);            }            result += sign * temp;            temp = 0;            sign = 1;        } else if(c == '-') {            if(!queue.isEmpty()) {                temp = calculateQueue(queue, cQueue, temp);            }            result += sign * temp;            temp = 0;            sign = -1;        } else if(c == '*' || c == '/'){            queue.add(temp);            cQueue.add(c);            temp = 0;        }    }    //handle the remaining part    if(temp != 0) {        if(!queue.isEmpty()) {            temp = calculateQueue(queue, cQueue, temp);        }        result += sign * temp;    }    return result;}//calculate previous temp with * or /public int calculateQueue(Queue<Integer> queue, Queue<Character> cQueue, int temp) {    int num = 0;    char sign2 = ' ';    if(!queue.isEmpty()) {        num = queue.poll();        sign2 = cQueue.poll();    }    while(!queue.isEmpty()) {        int num2 = queue.poll();        if(sign2 == '*') {            num = num * num2;        } else if(sign2 == '/') {            num = num/num2;        }        sign2 = cQueue.poll();    }    if(sign2 == '*') {            temp = num * temp;    }     else if(sign2 == '/') {            temp = num/temp;    }    return temp;    }}


0 0