2012-12-11 40 views
2

我正在爲我的一門課程進行任務,在該課程中,我將任何大小的「數字」作爲正確格式化的字符串。我使用三個堆棧,每個堆棧將每個數字作爲單獨的數字值。第一個堆棧將取第一個值,第二個堆棧取第二個值,第三個堆棧將結果值推入並彈出一個字符串。最後,字符串被打印到屏幕上。在Java中使用整數堆棧的添加

我的問題是這是我「攜帶一個」的能力 假設我在我的程序中添加了7和15,我的程序將彈出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); 
    } 
} 

我的問題已經回答,我已經得到它的工作感謝您的幫助。

回答

0

您需要添加一個新的變量來處理進樣

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的。

+0

謝謝我欣賞的幫助。我能夠使用你的邏輯,並寫出一些正確添加數字的東西,而不是說7 + 15 = 112。再次感謝您的先生。 – Lemuel

+0

@Lemuel如果您發現任何有用的答案,您可以選擇[接受](http://meta.stackexchange.com/a/146027/182516)。 – mtk

0

通過在前面的小長度字符串中加上0的數字使兩個字符串的長度相等。然後將這些字符放入堆棧中。之後,你會得到作家結果

 
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; 
     } 

    }