java - 使用整数堆栈在 Java 中进行加法

标签 java regex string stack addition

我正在为我的一门类(class)做作业,我将任何大小的“数字”作为格式正确的字符串。我使用三个堆栈,每个堆栈都将每个数字作为单独的数值。堆栈一取第一个值,堆栈二取第二个值,堆栈三将结果值压入并弹出到一个字符串中。最后将字符串打印到屏幕上。

我的问题是我“扛得住”的能力 假设我在我的程序中添加 7 和 15,我的程序会从堆栈 1 和 2 中弹出 7 和 5,分别将它们加在一起得到 12,这就是我的问题开始的地方,因为你们都看到了那个还在堆栈,我需要一种方法来识别一个实际上是十位的数字,依此类推以获得更大的数字。

这是我的整个加法方法的帖子,它从我的 main 方法中获取命令行参数,但这并不是真正重要的,我试图尽可能全面。

我希望我说的很透彻并且你们都理解了我的问题我很乐意进一步详细阐述这个主题。

private static void addlargeNumbers(String x, String y)throws ParseException{
    String o = x.replaceAll(",", "");
    String t = y.replaceAll(",", "");
    String r = "";
    Stack<Integer> one = new Stack<Integer>();
    Stack<Integer> two = new Stack<Integer>();
    Stack<Integer> resstack = new Stack<Integer>();


    int i = 0, j = 0;

    while(i < o.length()){
        one.push(Character.getNumericValue(o.charAt(i)));
        i++;
    }
    while(j < t.length()){
        two.push(Character.getNumericValue(t.charAt(j)));
        j++;
    }
    while(!one.isEmpty() || !two.isEmpty()){
        if(!one.isEmpty() && !two.isEmpty()){
            resstack.push(one.pop() + two.pop());

        }


        else if(one.isEmpty()){
            resstack.push(two.pop());
        }
        else{
            resstack.push(one.pop());
        }
    }
    while(!resstack.isEmpty()){
         r += resstack.pop();
    }

    if(!x.isEmpty() && !y.isEmpty()){
    System.out.printf("%s + %s = %s\n", x, y, r );
    }
    else if(x.isEmpty()){
        System.out.printf("%s = %s\n", y, r);
    }
    else{
        System.out.printf("%s = %s\n", x, r);
    }
}

我的问题已得到解答,我已经开始工作了,感谢您的帮助。

最佳答案

您需要添加一个新变量来处理进位

int  carry = 0;

然后,您只需在需要时计算并包含进位即可。

int carry=0, num1, num2, sum;
if(!one.isEmpty() && !two.isEmpty()){
    num1 = one.pop();
    num2 = two.pop();

    // Add previous carry if any. Would be `0` for first run
    sum = (num1 + num2 + carry)/10;

    // calculate and store it for next iteration
    carry = (num1 + num2 + carry)%10;

resstack.push(sum);
}

您还需要在与您添加的其他两个 if 类似的行中包含逻辑,以确保任一堆栈不为空。

关于java - 使用整数堆栈在 Java 中进行加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13815056/

相关文章:

java - getElementsByTagName 向下搜索所有级别的 XML 节点

java - XMPP 与 SIP 比较

regex - vscode中正则表达式的不完整量词

java - 正则表达式检查字符串是否仅包含数字不起作用

c++ - 如何将 std::string 复制到 unsigned char 数组?

java - 在制定规则后,我如何将事实 boolean 值放入槽中,谁可以计算它?

java - 登录spring核心应用程序?

python - 使用 re.finditer 不会返回所有匹配项

Ruby:拆分字符串而不删除分隔符

string - 在 bash 中,如何将 N 个参数连接在一起作为空格分隔的字符串