我有一些我一直在研究的 Java 代码。它仍处于粗糙阶段,所以我没有改变太多格式或尽可能简化它。
我需要我的代码能够处理饱和问题。目前,当输入如下方程式时:
2147483647
2
+
=
它会给我-2147483647并且不能正确饱和。反之亦然,如果我这样做:
-2147483647
2
-
=
它会给我+2147483647。
所以我知道它无法正常工作。
这是当前代码:
public class calculator {
private Stack<Integer> stack = new Stack<>();
public void prompt(String s) {
if (s.equals("+")) {
int input_1 = stack.pop();
int input_2 = stack.pop();
int outcome = input_2 + input_1;
stack.push(outcome);
}
else if (s.equals("-")) {
int input_1 = stack.pop();
int input_2 = stack.pop();
int outcome = input_2 - input_1;
stack.push(outcome);
}
else if (s.equals("=")) {
System.out.println(stack.peek());
}
else {
try {
int i = Integer.parseInt(s);
stack.push(i);
} catch (NumberFormatException e) {
System.out.println("Unrecognized operator or operand "+ s);
}
}
非常感谢任何帮助。我试图保持编码的整体结构相同。
实现饱和数学的最简单方法是对 long 执行操作,它们是 64 位,因此 32 位整数不会溢出,例如:
public static int saturatedAdd(int a, int b) {
long r = (long) a + b;
return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, r));
}
通过将
a
投射到 long,我们将获得正确的结果,而不会出现过流/欠流
下一步是使用 min/max 来绑定 long 值