Basic Calculator
2015-12-04 12:46
134 查看
这道题目真是花了九牛二虎之力才做对。。。= = 先转成逆波兰式再计算。。。这里的版本是完整的计算器功能,包括所有运算符, I && II都适用。不多说了,心很累,直接上代码:
public class Solution { public static int calculate(String s) { if (s == null || s.length() == 0) { return 0; } String str = s.replaceAll("\\s",""); List<String> postfix = convertToPostfix(str); Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < postfix.size(); i++) { String current = postfix.get(i); if (current.equals("+") || current.equals("-") || current.equals("*") || current.equals("/")) { Integer num1 = stack.pop(); Integer num2 = stack.pop(); if (current.equals("-")) { stack.push(num2-num1); } else if (current.equals("+")) { stack.push(num2 + num1); } else if (current.equals("*")) { stack.push(num2 * num1); } else { stack.push(num2 / num1); } } else { stack.push(Integer.parseInt(current)); } } return stack.pop(); } private static List<String> convertToPostfix(String str) { Stack<Character> stack = new Stack<Character>(); List<String> list = new ArrayList<String>(); for (int i = 0; i < str.length(); i++) { char current = str.charAt(i) ; StringBuilder sb = new StringBuilder(); if (Character.isDigit(current)) { while (i < str.length() && Character.isDigit(str.charAt(i))) { sb.append(str.charAt(i)); i++; } i--; list.add(sb.toString()); } else if (current == '(') { stack.push(current); } else if (current == ')') { while (!stack.isEmpty() && stack.peek() != '(') { list.add(Character.toString(stack.pop())); } stack.pop(); } else { if (stack.isEmpty()) { stack.push(current); } else { while (!stack.isEmpty()) { char temp = stack.peek(); if (temp == '(' || (current == '*' && (temp == '+' || temp == '-')) || (current == '/' && (temp == '+' || temp == '-'))) { break; } else { list.add(Character.toString(stack.pop())); } } stack.push(current); } } } while (!stack.isEmpty()) { list.add(Character.toString(stack.pop())); } return list; } }
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- android上改变listView的选中颜色
- String.intern
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- PostgreSQL ERROR: invalid escape string 解决办法
- 浅谈C++中的string 类型占几个字节
- 标准C++类string的Copy-On-Write技术
- C++实现string存取二进制数据的方法
- C#中string和StingBuilder内存中的区别实例分析
- PHP STRING 陷阱原理说明
- c#中 String和string的区别介绍
- C#实现的图片、string相互转换类分享
- asp.net String.IsNullOrEmpty 方法
- JavaScript中字符串(string)转json的2种方法
- C#中string用法实例详解
- C#中的DataSet、string、DataTable、对象转换成Json的实现代码
- JavaScript中的object转换成number或string规则介绍