如何修改RPN计算器代码实现饱和处理,将其转换为SRPN?
Java计算器饱和运算修正方案
以下是在保持你原有代码结构不变的前提下,针对加法和减法的饱和运算修改:
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; // 处理加法饱和:判断是否溢出 if (input_2 > 0 && input_1 > Integer.MAX_VALUE - input_2) { // 正溢出,饱和到最大值 outcome = Integer.MAX_VALUE; } else if (input_2 < 0 && input_1 < Integer.MIN_VALUE - input_2) { // 负溢出,饱和到最小值 outcome = Integer.MIN_VALUE; } else { 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 = input_2 + (-input_1),判断是否溢出 if (input_1 < 0 && input_2 > Integer.MAX_VALUE + input_1) { // input_1是负数,相当于加正数,正溢出 outcome = Integer.MAX_VALUE; } else if (input_1 > 0 && input_2 < Integer.MIN_VALUE + input_1) { // input_1是正数,相当于减正数,负溢出 outcome = Integer.MIN_VALUE; } else { 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); } } } }
关键逻辑说明
- 加法饱和:
- 当两个正数相加超过
Integer.MAX_VALUE时,结果固定为Integer.MAX_VALUE - 当两个负数相加小于
Integer.MIN_VALUE时,结果固定为Integer.MIN_VALUE
- 当两个正数相加超过
- 减法饱和:
- 当被减数是正数、减数是负数(相当于加正数)导致结果超过最大值时,固定为
Integer.MAX_VALUE - 当被减数是负数、减数是正数(相当于减正数)导致结果小于最小值时,固定为
Integer.MIN_VALUE
- 当被减数是正数、减数是负数(相当于加正数)导致结果超过最大值时,固定为
测试你给出的用例:
- 输入
2147483647、2、+、=,结果会是2147483647 - 输入
-2147483647、2、-、=,结果会是-2147483647
内容的提问来源于stack exchange,提问作者Faris
相关产品推荐
相关产品推荐

