java中使用整数堆栈的加法
我正在为我的一门课程做一项作业,在作业中,我把任意大小的“数字”作为一个正确格式的字符串输入。我使用三个堆栈,每个堆栈将每个数字作为单独的数值。堆栈一将获取第一个值,堆栈二将获取第二个值,堆栈三将结果值推入并弹出到字符串中。最后,字符串被打印到屏幕上 我的问题是我是否有能力“携带一个” 假设我在我的程序中加上7和15,我的程序将从堆栈1和堆栈2中分别弹出7和5,将它们相加得到12,这就是我的问题开始的地方,因为你们都看到一仍然在堆栈上,我需要一种方法来识别一实际上是一个十位的数字,以此类推,表示更大的数字 这里是我的整个添加方法的一个帖子,它从我的主方法中接收命令行参数,但这并不重要,我正试图尽可能彻底 我希望我做得很透彻,你们都理解我的问题。我很乐意进一步详细地阐述这个问题java中使用整数堆栈的加法,java,regex,string,stack,addition,Java,Regex,String,Stack,Addition,我正在为我的一门课程做一项作业,在作业中,我把任意大小的“数字”作为一个正确格式的字符串输入。我使用三个堆栈,每个堆栈将每个数字作为单独的数值。堆栈一将获取第一个值,堆栈二将获取第二个值,堆栈三将结果值推入并弹出到字符串中。最后,字符串被打印到屏幕上 我的问题是我是否有能力“携带一个” 假设我在我的程序中加上7和15,我的程序将从堆栈1和堆栈2中分别弹出7和5,将它们相加得到12,这就是我的问题开始的地方,因为你们都看到一仍然在堆栈上,我需要一种方法来识别一实际上是一个十位的数字,以此类推,表示
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);
}
}
private static void addlargeNumbers(字符串x,字符串y)引发异常{
字符串o=x.replaceAll(“,”和“”);
字符串t=y.replaceAll(“,”和“”);
字符串r=“”;
堆栈一=新堆栈();
堆栈二=新堆栈();
Stack resstack=新堆栈();
int i=0,j=0;
而(i
我的问题已经得到了回答,我已经开始工作了。谢谢您的帮助。您需要添加一个新变量来处理类似进位的操作
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);
}
您还需要在与您添加的其他两个
类似的行上包含逻辑,以注意其中一个堆栈是否为空。通过在前面的小长度字符串中添加0的数量,使两个字符串的长度相等。然后将字符放入堆栈中。之后,您将得到writer结果
public void makeEqualSize(String str1,String str2){
int num=Math.abs(str1.length()-str2.length());
String str3="";
if(str1.length() < str2.length()){
for(int i=0;i < num;i++){
str3+="0";
}
str1=str3+str1;
}else{
for(int i=0;i <num;i++){
str3+="0";
}
str2=str3+str2;
}
}
公共void MakequalSize(字符串str1、字符串str2){
int num=Math.abs(str1.length()-str2.length());
字符串str3=“”;
if(str1.length() 对于(int i=0;我感谢您我感谢您的帮助。我能够使用您的逻辑,写一些正确地添加数字的内容,而不是说7+15=112。再次感谢您,先生。@Lemuel如果您发现任何有帮助的答案,您可以选择。