leetcode:Basic Calculator
2015-06-13 13:30
357 查看
写一个支持+-和()的运算表达式的求解,因为题目比较简单,直接穷举计算,没有使用到优先级判断了
import java.util.HashMap; import java.util.Scanner; import java.util.Stack; public class Solution { public int calculate(String s) { Stack<Integer> nums = new Stack<Integer>(); Stack<Character> operation = new Stack<Character>(); int num = 0; //s = "(0+" + s + ")"; s = "(" + s + ")"; char[] ch = s.toCharArray(); for(int i = 0 ; i < ch.length;++i){ char c = ch[i]; if(Character.isDigit(ch[i])){ do{ num = num * 10 + ch[i++] - '0'; }while(i < ch.length && Character.isDigit(ch[i])); --i; nums.push(num); num = 0; continue; } if(c == ')'){ char topOp = operation.pop(); if(topOp == '('){ continue; } int b = nums.pop(); int a = nums.pop(); nums.push(doOp(a, topOp, b)); operation.pop(); }else if(c == '('){ operation.push(c); }else if(c == '+' || c == '-'){ char topOp = operation.peek(); if(topOp == '('){ operation.push(c); continue; } int a = nums.pop(); int b = nums.pop(); nums.push(doOp(b, topOp, a)); operation.pop(); operation.push(c); } } return nums.pop(); } public int doOp(int a, char op, int b){ if(op == '-') b = -b; return a + b; } public static void main(String[] args)throws Exception{ String s = ""; Scanner cin = new Scanner(System.in); Solution solution = new Solution(); while(!s.equals("bye")){ s = cin.nextLine(); int ans = solution.calculate(s); System.out.println(ans); } } }
相关文章推荐
- Zookeeper分布式锁
- 提问1
- [TMOOC]PhoneGap入门概述
- 第六单元
- hdu 3371 Connect the Cities
- 在写标签的时候要养成好习惯
- Activity has been destroyed
- dojo:如何为表格添加从数据库获得存储的下拉框
- 【C语言】字符串右循环移位
- div+css截取字符串在规定长度,超出部分用。。。代替
- TCP头部解析
- 文件翻译002片:Process Monitor帮助文档(Part 2)
- 给QT 程序的EXE文件添加图标
- SpringMVC学习(四)
- 电脑中的文件是在硬盘扇区中存储的形式
- 【c#第六次作业】猜猜看游戏
- 代码可读性的改良
- VMware虚拟机克隆Linux系统后找不到eth0网卡的问题
- lucas定理
- GoGo Tester 2.3.9详细使用教程