问题:
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
例如: ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路: 观察从逆波兰式到常规的calculation,总是遇到一个数字就将数字放入stack中,出现一个符号就将stack中的数据取出两个,做相应的计算,然后将得到的值再放入stack。到最后,这里只会有一个值在stack中,他就是最后的结果。
Python3
class Solution:
# @param {string[]} tokens The Reverse Polish Notation
# @return {int} the value
def evalRPN(self, tokens):
# Write your code here
# build a list as a stack
stack = []
# pick element from tokens
for element in tokens:
# if the element is a operator
if (element in ["+", "-", "/", "*"]):
if element == "*":
# implement the multiplication
new_value = stack.pop() * stack.pop()
stack.append(new_value)
elif element == "+":
# implement the addition
new_value = stack.pop() + stack.pop()
stack.append(new_value)
elif element == "-":
# obtain the value one by one
a = stack.pop()
b = stack.pop()
# implement the substraction
new_value = b - a
stack.append(new_value)
elif element == "/":
a = stack.pop()
b = stack.pop()
# if there is a minus number
if b*a < 0:
new_value = b / a
# if it is aliquant
if new_value *a != b:
new_value = new_value + 1
else:
new_value = b / a
stack.append(new_value)
else:
stack.append(int(element))
return stack.pop()
在编程过程中有几个小问题:
- python3数据类型: 此题提供了一个string,我们要将他切割成类似char类型。(注意,python3 是没有char这种类型的。)然后将得到的element与四个符号做匹配。如果不是,那么它就是一个数字,就要进行string向int的转化。(int(element))
string
number: int、float、bool、complex
List(列表)
Tuple(元组)
Sets(集合)
Dictionary(字典)
2.在python中,当 b / a 不是整除,它是向下取值的,也就是说1.2(1), 0.5(0), -1.2(-2), 注意负数的情况。取值原则是向下取整。所以我们需要在以上算法中判断是否整除(aliquant)。
但是在java中默认-3/2 =-1,3/2 = 1,即取值原则是向0靠拢。
Java
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
// Write your code here
Stack<Integer> stack = new Stack<Integer>();
String[] list = {"*","/","-","+"};
int value = 0;
int a, b;
for (int i = 0; i< tokens.length; i++)
{
if (tokens[i].equals("+"))
{
value = stack.pop() + stack.pop();
stack.push(value);
}else if (tokens[i].equals("*"))
{
value = stack.pop() * stack.pop();
stack.push(value);
}else if (tokens[i].equals("-"))
{
a = stack.pop();
b = stack.pop();
value = b - a;
stack.push(value);
}else if (tokens[i].equals("/"))
{
a = stack.pop();
b = stack.pop();
value = b / a;
stack.push(value);
}else
{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
-
java 数据类型:
内置数据类型: byte(8), short(16), int(32), long(64), float(32), double(64), boolean(1),char(16)
它们的封装类分别是:Byte,Short,Integer,Long,Float,Double,Boolean,Character。
引用数据类型: 对象、数组
String一个特殊的封装类数据
强制转化常用方法:
// int to byte
int i1 = 123;
byte b = (byte)i1;//强制类型转换为byte
// string to int
String MyNumber ="1234";
int MyInt = Integer.parseInt(MyNumber);
// int to string
int MyInt = 1234;
String MyString = "" + MyInt;
2.String类: ==用于比较两个String对象的地址,equals则用于比较两个String对象的内容(值),所以在我的code中用的是equals。
"=="操作符的作用:用于基本数据类型的比较;判断引用是否指向堆内存的同一块地址。
3.float 和 double
单精度(float) 存储占用4字节,也32位,有效位数为7位;
双精度(double)存储占用8字节,64位,有效位数为16位。